I have two maps:
Map map1;
Map map2;
I need to receive difference between these maps. Does exist ma
Building on Vlad's example to work with maps of different sizes
public static <K, V> Map<K, V> mapDiff(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(left.size() <= right.size() ? left.entrySet() : right.entrySet());
return difference;
}
Try using guava's MapDifference.
Simple way to do it. if you want complex way, you can change filter to compare value.
Map<String, Object> map1 = new HashMap<String, Object>() {{
put("A", "1");
put("B", "2");
put("C", "3");
}};
Map<String, Object> map2 = new HashMap<String, Object>() {{
put("A", "1");
put("B", "2");
put("D", "3");
}};
Map<String, Object> newList = map1.keySet().stream().filter(str -> !map2.containsKey(str)).collect(Collectors.toMap(v -> v, v -> map1.get(v)));
Map<String, Object> oldList = map2.keySet().stream().filter(str -> !map1.containsKey(str)).collect(Collectors.toMap(v -> v, v -> map2.get(v)));
System.out.println(newList);
System.out.println(oldList);
Set<Entry<String, Object>> diff = new HashSet<Entry<String, Object>>((map1.entrySet()));
diff.addAll(map2.entrySet());//Union
Set<Entry<String, Object>> tmp = new HashSet<Entry<String, Object>>((map1.entrySet()));
tmp.retainAll(map2.entrySet());//Intersection
diff.removeAll(tmp);//Diff
How about google guava?:
Maps.difference(map1,map2)
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