How can I best compare two HashMap
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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With