[英]compare & extract two Hashmap
我使用Scanner读取A.txt来生成A Hashmap,也使用相同的方法读取B.txt来获得B Hashmap。 这两个哈希图具有“ SOME”相同的键,并且希望彼此结合。 如果键相同,则打印出“键,值1,值2”。 到目前为止,这里是我:
public static void main (String[] args) throws FileNotFoundException {
Scanner scanner1 = new Scanner(new File("score.txt"));
Map<String, String> tolerance = new HashMap<>();
Scanner scanner2 = new Scanner(new File("Count2.txt"));
Map<String, String> Pdegree = new HashMap<>();
while (scanner1.hasNextLine()) {
String line = scanner1.nextLine();
String[] array = line.split("\t",2);
String Name = array[0];
String score = array[1];
tolerance.put(Name,score);
}
while (scanner2.hasNextLine()) {
String line2 = scanner2.nextLine();
String[] array2 = line2.split("\t",2);
String Name2 = array2[0];
String degree = array2[1];
Pdegree.put(Name2,degree);
}
for(Map.Entry<String, String> entry : tolerance.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
for(Map.Entry<String, String> entry2 : Pdegree.entrySet()) {
String key2 = entry2.getKey();
String value2 = entry2.getValue();
if(key==key2){
System.out.println(key2 + "\t" + value + "\t" + value2);
}
}
}
}
}
结果和错误消息都不会显示。 我的问题是如何从两个映射中提取具有各自值的相同键。 谢谢。
我自己找到了答案。 它应该是
if(key.equals(key2))
您可以使用map1.putAll(map2)
合并两个地图;
为什么不使用番石榴的多重地图? 我相信,如果您使用put all,并且它遇到两个相同的键,它只会向该键添加第二个值。 然后,您可以打印出所有键值对。 如果它具有相同的键和相同的值,则它取决于实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.