简体   繁体   English

如何从两个映射中删除相同的键

[英]How remove from two maps the identical keys

I created two maps in Java that contain the same type of Keys and Values:我在 Java 中创建了两个包含相同类型的键和值的映射:

Map<Position,Movement> A;
Map<Position,Movement> B;

I want to remove from them both (not create a new Map) the keys that are the same.我想从它们中删除(而不是创建新地图)相同的键。 I don't care if the value is different or not.我不在乎价值是否不同。 For example, if A has Position: a2 , Movement: n,n and B has Position: a2 , Movement: 1,2 those entries should be removed.例如,如果A有 Position: a2 ,运动: n,nB有 Position: a2 ,运动: 1,2这些条目应该被删除。

I wonder if there is a fast way to do that without iterating the shortest map and compare every single key.我想知道是否有一种快速的方法可以做到这一点,而无需迭代最短的 map 并比较每个键。

Thanks谢谢

You can use an Iterator on the keySet() of one of the maps and remove the element from the iterator and the other map if the key is present in the other map.如果密钥存在于另一个 map 中,您可以在其中一个映射的keySet()上使用Iterator ,并从迭代器和另一个 map 中删除元素。

Iterator<String> itr = map1.keySet().iterator();
String key;
while (itr.hasNext()) {
    key = itr.next();
    if (map2.containsKey(key)) {
        itr.remove();
        map2.remove(key);
    }
}

Demo:演示:

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, String> map1 = new HashMap<String, String>();
        map1.put("a", "1");
        map1.put("b", "1");
        map1.put("x", "1");
        map1.put("c", "1");
        map1.put("z", "1");
        map1.put("d", "1");

        Map<String, String> map2 = new HashMap<String, String>();
        map2.put("w", "1");
        map2.put("x", "1");
        map2.put("b", "1");
        map2.put("y", "1");
        map2.put("c", "1");
        map2.put("z", "1");

        Iterator<String> itr = map1.keySet().iterator();
        String key;
        while (itr.hasNext()) {
            key = itr.next();
            if (map2.containsKey(key)) {
                itr.remove();
                map2.remove(key);
            }
        }

        System.out.println(map1);
        System.out.println(map2);
    }
}

Output: Output:

{a=1, d=1}
{w=1, y=1}

[Update] [更新]

Solution using Stream :使用Stream解决方案:

map1.keySet()
    .stream()
    .filter(k -> map2.containsKey(k))
    .collect(Collectors.toList())
    .forEach(k -> {
        map1.remove(k);
        map2.remove(k);
    });

[Another Update] [另一个更新]

Given below is a compact version (Thanks to Holger ) of the first solution:下面给出了第一个解决方案的紧凑版本(感谢Holger ):

for (Iterator<String> itr = map1.keySet().iterator(); itr.hasNext();) {
    if (map2.keySet().remove(itr.next())) {
        itr.remove();
    }
}

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

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