Skip to content

Compare Two HashMap objects (Map) in Java Example

This example shows how to compare two HashMap in Java using the equals method. The example also shows how to compare HashMap keys or values with another HashMap.

How to compare two HashMap objects in Java using the equals method?

The equals method of the Map compares two map objects for equality. It returns true if the mappings of both the map are the same.

In other words, the equals method of the Map returns true if and only if the maps have the same key-value pairs.

The below given example shows how to compare the map objects using the equals method.

Output

Important Note: The order of the HashMap mappings does not have to be the same as you can see from the above example.

How to compare two HashMap keys?

We can check if two HashMap objects have the same keys by comparing their keys obtained using the keySet method. The keySet method returns a Set view of all keys contained in the HashMap.

We can use the equals method of the Set to compare the keys as given below.

Output

How to compare HashMap values?

We can compare if values contained in the map objects are the same or not by converting all map values to Set and then use the equals method of the Set as given below.

Output

Important Note: The Set is a collection of unique values. If your HashMap contains duplicate values, the above approach will remove all duplicates values and only checks that the values contained in both the map objects are equal.

It might be possible that one map contains one value mapped to many different keys while the other does not. In that case, even if the map objects are different, the above approach returns true for values.

All of the above given comparisons work if and only if the key and value objects have implemented the equals methods. If your HashMap has custom class objects either as keys or values, the custom class has to implement the equals and hashCode methods.

This example is a part of the HashMap in Java tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.