Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two hashmaps for equal values and same key sets?

How can I best compare two HashMaps, 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?

like image 634
membersound Avatar asked Jan 07 '14 10:01

membersound


People also ask

Do Hashmaps allow for duplicates?

HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.

Can a map have two values with the same key?

However, none of the existing Java core Map implementations allow a Map to handle multiple values for a single key. As we can see, if we try to insert two values for the same key, the second value will be stored, while the first one will be dropped.

What happen if we add same key with different values to HashMap?

If you try to insert the duplicate key, it will replace the element of the corresponding key. HashMap is similar to HashTable, but it is unsynchronized. It allows to store the null keys as well, but there should be only one null key object and there can be any number of null values.


1 Answers

Simply use :

mapA.equals(mapB);

Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings

like image 169
user2336315 Avatar answered Oct 16 '22 08:10

user2336315