Java 用键比较两个 hashmap 值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18546211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 08:55:34  来源:igfitidea点击:

Comparing two hashmap value with keys

javahashmapcomparison

提问by Vignesh Vino

I have two HashMaps.

我有两个HashMaps

HashMap<String, String> hMap=new HashMap<String, String>();
hMap.put("1","one");
hMap.put("2", "two");
hMap.put("3", "three");
hMap.put("4", "four");

HashMap<String, String> hMap2=new HashMap<String, String>();
hMap2.put("one", "");
hMap2.put("two", "");

I want to compare the key of hMap2 with hMap which are not equal I need to put it in another hashMap.For this I tried something like this.

我想将 hMap2 的键与不相等的 hMap 进行比较,我需要将它放在另一个 hashMap 中。为此,我尝试了这样的操作。

HashMap<String, String> hMap3=new HashMap<String, String>();
Set<String> set1=hMap.keySet();
Set<String> set2=hMap2.keySet();

Iterator<String> iter1=set1.iterator();
Iterator<String> iter2=set2.iterator();
String val="";
while(iter1.hasNext()) {

    val=iter1.next();
    System.out.println("key and value in hmap is "+val+" "+hMap.get(val));

    iter2=set2.iterator();

    while(iter2.hasNext()) {
        String val2=iter2.next();
        System.out.println("val2 value is "+val2);

        if(!hMap.get(val).equals(val2)) {
            hMap3.put(val, hMap.get(val));
            System.out.println("value adding");

        }
    }
}
System.out.println("hashmap3 is "+hMap3);

The output I'm getting here is

我在这里得到的输出是

hashmap3 is {3=three, 2=two, 1=one, 4=four}

My Expected output is

我的预期输出是

hashmap3 is {3=three, 4=four}

Please correct my logic.Thanks in advance

请纠正我的逻辑。提前致谢

采纳答案by Rohit Jain

You are really complicating your task. You don't need to iterate over your 2nd map at all. You can use Map#containsKey()method to check whether values in the first map is the key in the 2nd map.

你真的让你的任务复杂化了。您根本不需要遍历第二张地图。您可以使用Map#containsKey()method 来检查第一个映射中的值是否是第二个映射中的键。

So, you just need to iterate over the first map. Since you want both keys and values, you can iterate over the Map.Entryof the first map. You get that using Map#entrySet().

所以,你只需要遍历第一张地图。由于您需要键和值,您可以迭代Map.Entry第一个地图的 。你可以使用Map#entrySet().

Since the values of the first map is the key in your second, you need to use the containsKeymethod on the Map.Entry#getValue()method:

由于第一张地图的值是第二张地图的关键,因此您需要在containsKey方法上使用该Map.Entry#getValue()方法:

for (Entry<String, String> entry: hMap.entrySet()) {
    // Check if the current value is a key in the 2nd map
    if (!hMap2.containsKey(entry.getValue()) {

        // hMap2 doesn't have the key for this value. Add key-value in new map.
        hMap3.put(entry.getKey(), entry.getValue());
    }
}