I'm using MultiValuedMaps from apache common i.e. org.apache.commons.collections4.MultiValuedMap;
I have two MultiValuedMaps as follows:
MultiValuedMap<String, Integer> m1 = new ArrayListValuedHashMap<>();
m1.put("a",23);
m1.put("a",24);
MultiValuedMap<String, Integer> m2 = new ArrayListValuedHashMap<>();
m2.put("a",24);
m2.put("a",23);
What is the most efficient way to compare both the keys and values?
I tried m1.equals(m2), but it doesn't work.
CodePudding user response:
m1.equals(m2)
should work.
Btw. you can try to use m1.toString().equals(m2.toString())
it will convert your MultiValuedMap
to String
objects and make equals operation on them. But be careful with toString()
as it will depends on map objects order.
CodePudding user response:
If the values in your map are an arrays, it will be more complicated, you should wrote your own method, which will look like this (be aware of map values sorting):
private static boolean areEqual(MultiValuedMap<String, String[]> first, MultiValuedMap<String, String[]> second) {
if (first.size() != second.size() && !first.keySet().containsAll(second.keySet())) {
return false;
}
List<String[]> firstValues = new ArrayList<>(first.values());
List<String[]> secondValues = new ArrayList<>(second.values());
if (firstValues.size() != secondValues.size()) {
return false;
}
for (int i = 0; i < firstValues.size(); i ) {
String[] firstArr = firstValues.get(i);
String[] secondArr = secondValues.get(i);
Arrays.sort(firstArr);
Arrays.sort(secondArr);
if (!Arrays.equals(firstArr, secondArr)) {
return false;
}
}
return true;
}