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
This question is old, but still relevant.
If you want to compare two maps by their values matching their keys, you can do as follows:
public static boolean mapEquals(Map leftMap, Map rightMap) {
if (leftMap == rightMap) return true;
if (leftMap == null || rightMap == null || leftMap.size() != rightMap.size()) return false;
for (K key : leftMap.keySet()) {
V value1 = leftMap.get(key);
V value2 = rightMap.get(key);
if (value1 == null && value2 == null)
continue;
else if (value1 == null || value2 == null)
return false;
if (!value1.equals(value2))
return false;
}
return true;
}