繁体   English   中英

将两个hashmap值与键进行比较

[英]Comparing two hashmap value with keys

我有两个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", "");

我想比较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);

我得到的输出是

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

我的预期输出是

hashmap3 is {3=three, 4=four}

请纠正我的逻辑。谢谢

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

所以,你只需要迭代第一张地图。 由于您需要键和值,因此可以迭代第一个映射的Map.Entry 你可以使用Map#entrySet()获得它。

由于第一个映射的值是第二个映射的键,因此需要在Map.Entry#getValue()方法上使用containsKey方法:

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

暂无
暂无

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

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