Reputation: 29371
I need to write a small snippet of code where I need to check contents of a map (key value) if it exists in another map , remove it from the map
E.g
Map1:
1=>obj1
2=>obj21
3=>obj3
4=>obj4
Other map Map2:
10=>obj10
20=>obj20
2=>obj2
30=>obj30
3=>obj3
The result of fun (Map1, Map2) after it executes it has the following ouput
Map2:
10=>obj10
2=>obj2
20=>obj20
30=>obj30
Is iterating over the smaller map and checking contents (key, value) is iterating over the smaller map and checking the key and contents in the bigger map the most efficient way to go about it.
Upvotes: 1
Views: 906
Reputation: 651
private static <K, V> removeDuplicates(Map<K, V> map1, Map<K, V> map2) {
for (K key : map1.keySet()) {
V val1 = map1.get(key);
V val2 = map2.get(key);
if (val2 != null && val2.equals(val1)
map2.remove(key);
}
}
Upvotes: 0
Reputation: 12770
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);
}
Upvotes: 1
Reputation: 565
m1.entrySet().removeAll(m2.entrySet());
where m1 is the Map to be modified, and m2 is the map with the mappings that need to be removed from m1.
Upvotes: 2