tags:

views:

141

answers:

4

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.

A: 

See java.util.Collection

boolean removeAll(Collection<?> c)
diciu
Map != Collection
tuergeist
Map has keySet() method that returns a Set. Set extends Collection.
diciu
entrySet() rather than keySet(). He wants to find and remove by complete mappings, not by keys only.
Bartosz Klimek
+2  A: 
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.

Bartosz Klimek
+1  A: 
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);
}
pgras
A: 
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);
    }
}
Brian Bassett