[英]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.