I have two maps:
Map<String, Object> map1;
Map<String, Object> map2;
I need to receive difference between these maps. Does exist may be apache utils how to receive this difference? For now seems need take entry set of each map and found diff1 = set1 - set2 and diff2 = set2- set1. After create summary map =diff1 + diff2 It looks very awkwardly. Does exist another way? Thanks.
Building on Vlad's example to work with maps of different sizes
Here is a simple snippet you can use instead of massive Guava library:
Check out the whole working example
How about google guava?:
Try using guava's MapDifference.
If I understood well you are trying to calculate symmetric difference beetween the two maps entry sets.
Considering the awkward behavior you mentioned, let's take a closer look at the above code behavior. For example if we take the numerical example from the above given link:
After you calculate the difference as shown, the output:
gives:
which is the correct result. But, if we do it like this:
the same algorithm gives the following output:
which is not correct (and might be described as awkward :) )
In the first example the map is filled with int values wich are automatically boxed to Integer values.
The class Integer has its own implementation of equals and hashCode methods.
The class CustomInteger does not implement these methods so it inherits them from the omnipresent Object class.
The API doc for the removeAll method from the Set interface says the following:
In order to determine which elements are contained in both collections, the removeAll method uses the equals method of the collection element.
And that's the catch: Integer's equals method returns true if the two numeric values are the same, while Object's equals method will return true only if it is the same object, e.g. :
If it's still a bit fuzzy I strongly suggest reading the following tutorials: