Checking map content on another map in java
I need to write a small piece of code where I need to check the contents of the map (key value), if it exists on another map, remove it from the map
For instance,
Map1:
1=>obj1
2=>obj21
3=>obj3
4=>obj4
Other Map2:
10=>obj10
20=>obj20
2=>obj2
30=>obj30
3=>obj3
Fun result (Map1, Map2) after executing it has the following output
map2:
10=>obj10
2=>obj2
20=>obj20
30=>obj30
Iterates over the smaller map and checks the contents (key, value) iterates over the smaller map and checks the key and contents in the larger map the most efficient workaround.
+1
a source to share
4 answers
private static <K, V> void fun(Map<K, V> a, Map<K, V> b) {
Map<K, V> shortestMap = a.size() < b.size() ? a : b;
Map<K, V> longestMap = a.size() > b.size() ? a : b;
Set<Entry<K, V>> shortestMapEntries = shortestMap.entrySet();
Set<Entry<K, V>> longestMapEntries = longestMap.entrySet();
longestMapEntries.removeAll(shortestMapEntries);
}
+1
a source to share