java - 将 Hashmap 上的列表添加到另一个列表时出现问题
问题描述
将列表从一个哈希映射的值添加到另一个哈希映射的问题
基本上,我有 2 个哈希图(map1 和 map2),它们都有相同的键(0-500 的整数),但值不同。我想要做的是使用 map1 的值,它是一个字符串,作为键和 map2 的值,它是一个列表,作为值。添加 map1 作为键是有效的,没问题,但是当我尝试将 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.put(map1.get(i), map2.get(i));
和
map.put(map1.get(i), t);
并且 -
System.out.print(map2.get("burrito"));
和
System.out.print(map.get("burrito"));
此外,您正在尝试使用String
您所说的密钥int
类型来获取地图的值,请检查。
推荐阅读
- git - 为 git 历史中的所有提交更改 git 子模块的远程存储库
- php - 提交时检查 $_FILES 变量是否为空 eg: variableIsEmpty($_FILES["icon"])
- python - Pyspark coalesce vs coalesce:秘密相同或只是不幸的命名?
- kotlin - Kotlinx 序列化器和单值域类型
- vue.js - 在 vuetify 数据表中显示切换开关的状态
- spring-boot - 使用 OpenTracing 向 Jaeger 报告 Spring Cloud Sleuth 的应用程序未使用 BraveTracer
- java - 将数据保存到 ArrayList 的高效代码
- ios - 如何切换打开关闭uitableViewCell
- python - 有没有办法将 numpy.where() 用于将 NaN 值作为无数据的栅格数据?
- c# - 如何使用 NUnit 断言该集合是 IReadOnlyCollection