Every Java collection implements the equals() method, which compares it with another collection. In the case of Map, two maps are considered equal (map1.equals(map2) returns true) when:
- Both are Map objects
- One map has the same set of key-value pairs as another map
Here is the code that illustrates the definition:
Map<Integer, String> map1 = new HashMap<>();
map1.put(1, null);
map1.put(2, "s2");
map1.put(3, "s3");
Map<Integer, String> map2 = new HashMap<>();
map2.put(1, null);
map2.put(2, "s2");
map2.put(3, "s3");
System.out.println(map2.equals(map1)); //prints: true
map2.put(1, "s1");
System.out.println(map2.equals(map1)); //prints: false
If you think about it, the map1.equals(map2) method returns exactly the same result as the map1.entrySet().equals(map2.entrySet()) method, because the entrySet() method returns Set<Map.Entry<K,V> and we know (see the subsection Compare with another collection for Set) that two sets are equal when each element of one set is contained in another set.
If two maps are equal, their hashCode() methods return the same integer value. But the equality of hashCode() results does not guarantee that the maps are equal. We have talked about the reason for that while discussing the hashCode() method's implementation for the elements of the Set collection in the previous section.
If two maps are not equal and there is a need to find out exactly what the difference is, there are a variety of ways to do it:
map1.entrySet().containsAll(map2.entrySet());
map1.entrySet().retainAll(map2.entrySet());
map1.entrySet().removeAll(map2.entrySet());
map1.keySet().containsAll(map2.keySet());
map1.keySet().retainAll(map2.keySet());
map1.keySet().removeAll(map2.keySet());
map1.values().containsAll(map2.values());
map1.values().retainAll(map2.values());
map1.values().removeAll(map2.values());
Using any combination of these methods, one can get the full picture of the difference between the two maps.