【发布时间】:2019-09-09 06:59:48
【问题描述】:
问题将一个列表从一个哈希映射的值添加到另一个哈希映射的值
基本上,我有 2 个哈希图(map1 和 map2),它们都有相同的键(0-500 的整数),但值不同。我想要做的是使用 map1 的值,它是一个字符串,作为键和 map2 的值,它是一个列表,作为值。将 map1 添加为 key 可以正常工作,没问题,但是当我尝试将 map2 的值添加为 map 的值时,它只是返回为 null。
这是一个家庭作业项目,我们有 2 个 .csv 文件,一个带有标签,另一个带有假图像文件名,并且必须能够通过图像标签或图像文件名进行搜索。
Map<String, List<String>> map = new HashMap<String, List<String>>();
@SuppressWarnings({ "resource", "null", "unlikely-arg-type" })
public ImageLabelReader(String labelMappingFile, String imageMappingFile) throws IOException {
Map<Integer, String> map1 = new HashMap<Integer, String>();
Map<Integer, List<String>> map2 = new HashMap<Integer, List<String>>();
BufferedReader labelIn = new BufferedReader(new FileReader(labelMappingFile));
BufferedReader imageIn = new BufferedReader(new FileReader(imageMappingFile));
String row;
String[] rowArray;
while ((row = labelIn.readLine()) != null) {
rowArray = row.split(" ", 2);
map1.put(Integer.parseInt(rowArray[0]), rowArray[1]);
}
labelIn.close();
while ((row = imageIn.readLine()) != null) {
rowArray = row.split(" ", 2);
if(map2.containsKey(Integer.parseInt(rowArray[1]))) {
List<String> tempList = map2.get(Integer.parseInt(rowArray[1]));
tempList.add(rowArray[0]);
} else {
List<String> l = new ArrayList<String>();
l.add(rowArray[0]);
map2.put(Integer.parseInt(rowArray[1]), l);
}
}
imageIn.close();
List<String> t = new ArrayList<String>();
for(int i = 0; i < map1.size(); i++) {
t.clear();
for(String s : map2.get(i)) {
t.add(s);
System.out.println(t);
}
map.put(map1.get(i), map2.get(i));
}
System.out.println(map.containsKey("burrito"));
System.out.print(map2.get("burrito"));
}
当输出应为“True [包含字符串的列表]”时,输出为“True null”
【问题讨论】:
-
你打电话给
map.containsKey,但是map2.get。那是错字吗?你的意思是访问同一个地图吗?应该是map.get("burrito") -
你不应该使用
map.put(map1.get(i), t);而不是map.put(map1.get(i), map2.get(i)); -
这是一个错误——我已经完全掩盖了这一点......现在我看到它有效。感谢您的帮助!
-
map2.get("burrito") map2 的键是整数。而“burrito”是一个字符串
标签: java list arraylist hashmap