114. Comparing two maps

Comparing two maps is straightforward as long as we rely on the Map.equals() method. When comparing two maps, this method compares the keys and values of them using the Object.equals() method.

For example, let's consider two maps of melons having the same entries (the presence of equals() and hashCode() is a must in the Melon class):

public class Melon {

private final String type;
private final int weight;

// constructor, getters, equals(), hashCode(),
// toString() omitted for brevity
}

Map<Integer, Melon> melons1Map = new HashMap<>();
Map<Integer, Melon> melons2Map = new HashMap<>();
melons1Map.put(1, new Melon("Apollo", 3000));
melons1Map.put(2, new Melon("Jade Dew", 3500));
melons1Map.put(3, new Melon("Cantaloupe", 1500));
melons2Map.put(1, new Melon("Apollo", 3000));
melons2Map.put(2, new Melon("Jade Dew", 3500));
melons2Map.put(3, new Melon("Cantaloupe", 1500));

Now, if we test melons1Map and melons2Map for equality, then we obtain true:

boolean equals12Map = melons1Map.equals(melons2Map); // true

But this will not work if we use arrays. For example, consider the next two maps:

Melon[] melons1Array = {
new Melon("Apollo", 3000),
new Melon("Jade Dew", 3500), new Melon("Cantaloupe", 1500)
};
Melon[] melons2Array = {
new Melon("Apollo", 3000),
new Melon("Jade Dew", 3500), new Melon("Cantaloupe", 1500)
};

Map<Integer, Melon[]> melons1ArrayMap = new HashMap<>();
melons1ArrayMap.put(1, melons1Array);
Map<Integer, Melon[]> melons2ArrayMap = new HashMap<>();
melons2ArrayMap.put(1, melons2Array);

Even if melons1ArrayMap and melons2ArrayMap are equal, Map.equals() will return false:

boolean equals12ArrayMap = melons1ArrayMap.equals(melons2ArrayMap);

The problem originates in the fact that the array's equals() method compares identity and not the contents of the array. In order to solve this problem, we can write a helper method as follows (this time relying on Arrays.equals(), which compares the contents of the arrays):

public static <A, B> boolean equalsWithArrays(
Map<A, B[]> first, Map<A, B[]> second) {

if (first.size() != second.size()) {
return false;
}

return first.entrySet().stream()
.allMatch(e -> Arrays.equals(e.getValue(),
second.get(e.getKey())));
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.56.29