How to compare two hash maps in Java

Hi I am working with HashMap in java and I have a scenario where I need 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 final hashmap will contain the key as the First HashMap1 value and the value as the second HashMap2 value.

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

      

+3


source to share


4 answers


Just iterate over the keys HashMap1

, and for each key, check if it's present in HashMap2

. If present, add 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));
    }
}

      

+7


source


Iterate over the keys of the first card and place the values ​​on the new card if the second card 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);
    }
}

      

+1


source


HashMap has a method called entrySet()

that returns an object representing the contents of the map as a set of key-value pairs.

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

      

You have to iterate over this set using the keys to search the second map and then put the results into the "result set".

I assume you have it set that the values in the first set will be unique OR you don't mind the records being overwritten in the output.

Note that the iterator moves through the set in an unspecified order, so if they are overwritten this method does not guarantee which values ​​overwrite other values.

+1


source


You can use the keyset of both cards to intersect them with:

boolean     retainAll(Collection<?> c)

      

and then iterating using that intersection over the maps creating your solution.

0


source







All Articles