Reputation: 1
I have two different hashmap with Map<String, ArrayList> format , how to compare key first and then comparing their values are same or not.
Upvotes: 0
Views: 4063
Reputation: 719576
If you are simply trying to test if all keys and all values in the maps are equal according to the equals(Object)
method, then this should work:
boolean equalMaps = map1.equals(map2);
If want to test that entries with the same key have equal values, then:
boolean equalValues = map1.entrySet().stream()
.filter(e -> map2.get(e.getKey()) != null)
.allMatch(e -> e.getValue().equals(map2.get(e.getKey()));
(Note: the above is not the most efficient solution possible. The filter
eliminates cases where the key is not present in map2
which would otherwise cause the allMatch
to fail.)
And there are other solutions for other tests that you may want to perform.
Note the above solutions assume that the value type's equals(Object)
method has the right semantics for your vaguely stated "comparing their values are same or not" requirement.
Upvotes: 2