membersound membersound - 1 year ago 346
Java Question

Comparing two hashmaps for equal values and same key sets?

How can I best compare two

s, if I want to find out if none of them contains different keys than the other, and if the values of that keys match each other.

Map<objA, objB> mapA = new HashMap<objA, objB>();
mapA.put("A", "1");
mapA.put("B", "2");

Map<objA, objB> mapB = new HashMap<objA, objB>();
mapB.put("D", "4");
mapB.put("A", "1");

When comparing A with B, it should fail due to different keys B and D.

How could I best compare non-sorted hashmaps?

Answer Source

Make an equals check on the keySet() of both HashMaps.


If your Map contains String keys then it is no problem, but if your Map contains objA type keys then you need to make sure that your class objA implements equals().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download