Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to receive difference of maps in java?

Tags:

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.

like image 314
user710818 Avatar asked Oct 04 '12 06:10

user710818


2 Answers

How about google guava?:

Maps.difference(map1,map2)
like image 111
Koerr Avatar answered Oct 20 '22 06:10

Koerr


Here is a simple snippet you can use instead of massive Guava library:

public static <K, V> Map<K, V> mapDifference(Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right) {
    Map<K, V> difference = new HashMap<>();
    difference.putAll(left);
    difference.putAll(right);
    difference.entrySet().removeAll(right.entrySet());
    return difference;
}

Check out the whole working example

like image 38
Vlad Holubiev Avatar answered Oct 20 '22 05:10

Vlad Holubiev