How to compare two maps by their values? I have two maps containing equal values and want to compare them by their values. Here is an example:
Map a = ne
To see if two maps have the same values, you can do the following:
Collection values()
viewsList
Collections.sort
those listsequals
Something like this works (though its type bounds can be improved on):
static >
boolean valuesEquals(Map,V> map1, Map,V> map2) {
List values1 = new ArrayList(map1.values());
List values2 = new ArrayList(map2.values());
Collections.sort(values1);
Collections.sort(values2);
return values1.equals(values2);
}
Test harness:
Map map1 = new HashMap();
map1.put("A", "B");
map1.put("C", "D");
Map map2 = new HashMap();
map2.put("A", "D");
map2.put("C", "B");
System.out.println(valuesEquals(map1, map2)); // prints "true"
This is O(N log N)
due to Collections.sort.
To test if the keys are equals is easier, because they're Set
:
map1.keySet().equals(map2.keySet())