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


m1.entrySet().removeAll(m2.entrySet());

      



where m1 is the Map to be modified and m2 is the display with the display to be removed from m1.

+2


a source


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


See java.util.Collection

boolean removeAll(Collection<?> c)

      

0


a source


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);
    }
}

      

0


a source







All Articles