Comparing two hashmap values ​​with keys

I have two 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 hMap2 key with hMap, which are not equal. I need to put it in another hashMap. For this, I tried something like this.

 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 get here is

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

My expected result

 hashmap3 is {3=three, 4=four} 

Please correct my logic. thanks in advance

+4
source share
1 answer

You really complicate your task. You do not need to sort out the second card. You can use the Map#containsKey() method to check if the values ​​on the first map are key in the second map.

So, you just need to iterate over the first card. Since you need both keys and values, you can Map.Entry over Map.Entry first map. You will get this with Map#entrySet() .

Since the values ​​of the first map are key in your second, you need to use the containsKey method for the Map.Entry#getValue() method:

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

Source: https://habr.com/ru/post/1499905/


All Articles