简体   繁体   English

在Java中检查另一个地图中的地图内容

[英]Checking contents of a map in another map in java

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 我需要编写一小段代码,在其中需要检查地图的内容(键值)是否存在于另一张地图中,然后将其从地图中删除

Eg 例如

Map1: 地图1:

1=>obj1
2=>obj21
3=>obj3 
4=>obj4

Other map Map2: 其他地图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 fun(Map1,Map2)执行后的结果具有以下输出

Map2: 地图2:

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. 在较小的地图上进行迭代并检查内容(键,值)在较小的地图上进行迭代并检查较大的地图中的键和内容是解决此问题的最有效方法。

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

其中m1是要修改的地图,m2是需要从m1中删除的映射的地图。

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

参见java.util.Collection

boolean removeAll(Collection<?> c)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM