簡體   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