How to compare two Hash Maps in Java

32,765

Solution 1

Just iterate on the keys of HashMap1, and for each key, check if it's present in HashMap2. If it's present, add the values to HashMap3 :

final Map<String, String> hm1 = new HashMap<String, String>();
hm1.put("BOF", "SAPF");
hm1.put("BOM", "SAPM");
hm1.put("BOL", "SAPL");

final Map<String, String> hm2 = new HashMap<String, String>();
hm2.put("BOF", "Data1");
hm2.put("BOL", "Data2");

final Map<String, String> hm3 = new HashMap<String, String>();

for (final String key : hm1.keySet()) {
    if (hm2.containsKey(key)) {
        hm3.put(hm1.get(key), hm2.get(key));
    }
}

Solution 2

Iterate over the keys of the first map and put the values in your new map, if the second map has a value for the same key.

Map map3 = new HashMap();
for (Object key : map1.keySet()) {
    Object value2 = map2.get(key);
    if (value2 != null) {
        Object value1 = map1.get(key);
        map3.put(value1, value2);
    }
}

Solution 3

HashMap has an method called entrySet() that returns an object that represents the content of the map as a set of key-value pairs.

public Set<Map.Entry<K,V>> entrySet()

You should iterate through that set using the keys to look up in the second map and then putting the results in the 'result set'.

I assume you have a established that the values in the first set will be unique OR you don't mind that entries might get overwritten in the output.

Notice that the iterator moves through the set in an unspecified order so if there are overwrites this method won't guarantee which values overwrite which other values.

Share:
32,765
Utsav
Author by

Utsav

Software Engineer

Updated on July 05, 2022

Comments

  • Utsav
    Utsav almost 2 years

    Hi I am working with HashMap in java and i have a scenario where i have to compare 2 HashMaps

    HashMap1:
    Key: BOF   Value: SAPF
    Key: BOM   Value: SAPM
    Key: BOL   Value: SAPL
    
    HashMap2:
    Key: BOF   Value: Data1
    Key: BOL   Value: Data2
    

    And after comparing these two hashmaps my resulting hashmap will contain the Key as a Value of First HashMap1 and Value as a Value of second HashMap2.

    HashMap3:
    Key: SAPF  Value: Data1
    Key: SAPL  Value: Data2