How to get the difference of two maps based on the key set?

snaggs picture snaggs · May 3, 2014 · Viewed 9.2k times · Source

I have two maps:

Map<String, Sample> newMap = convertJSONObjectToSampleMap(newMapStr);
Map<String, Sample> oldMap = convertJSONObjectToSampleMap(oldMapStr);

the Sample is some custom class

The newMap has keys: [1,2,3,4,5] The oldMap has keys: [2,3,4,5,8]

What is the best way to get difference between them, .e, get Samples with keys: 1 and 8?

I thought to use Collections and extract Set<>:

Set<String> newSet = newMap.keySet();
Set<String> oldSet = oldMap.keySet();

Thank you,

Answer

Alexis C. picture Alexis C. · May 3, 2014

What you want is called the symmetric difference.

enter image description here

Guava provides such a method.

Set<String> diff = Sets.symmetricDifference(newSet, oldSet);

Then just iterate through the set get the samples.

List<Sample> samples = new ArrayList<>();
for(String key : diff){
    if(oldMap.containsKey(key)){
        samples.add(oldMap.get(key));
    } else {
        samples.add(newMap.get(key));
    }
}

You can also do it with the official API, basically the symmetric difference is the union minus the intersection of both sets, but why reinvent the wheel?

Using an external dependency can be bad if you're using only one method, but Guava provides a lot of useful features that are a must.