简体   繁体   English

比较并提取两个Hashmap

[英]compare & extract two Hashmap

I used Scanner to read through A.txt to generate A Hashmap, also same method to read through B.txt to have B Hashmap. 我使用Scanner读取A.txt来生成A Hashmap,也使用相同的方法读取B.txt来获得B Hashmap。 These two hashmap have the "SOME" same key and would like to combine with each other. 这两个哈希图具有“ SOME”相同的键,并且希望彼此结合。 If the key is are the same, print out "key, value1, value2". 如果键相同,则打印出“键,值1,值2”。 Here is I have so far : 到目前为止,这里是我:

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);
            }
    }
 }
}
}

Neither results nor error messages would show. 结果和错误消息都不会显示。 My question is how to extract the same key with respective values from two maps. 我的问题是如何从两个映射中提取具有各自值的相同键。 Thanks. 谢谢。

I found the answer by myself. 我自己找到了答案。 It should be 它应该是

 if(key.equals(key2))

您可以使用map1.putAll(map2)合并两个地图;

Why not use Guava's multimap? 为什么不使用番石榴的多重地图? I believe that if you use put all and it comes across two identical keys, it simply adds a second value to the key. 我相信,如果您使用put all,并且它遇到两个相同的键,它只会向该键添加第二个值。 Then you can print out all teh key value pairs. 然后,您可以打印出所有键值对。 If it has identical key and identical value what it does is implementation dependent. 如果它具有相同的键和相同的值,则它取决于实现。

https://guava-libraries.googlecode.com/svn/tags/release03/javadoc/com/google/common/collect/Multimap.html#put(K , V) https://guava-libraries.googlecode.com/svn/tags/release03/javadoc/com/google/common/collect/Multimap.html#put(K,V

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM