使用lamda表达式Java比较两个地图

时间:2018-07-04 15:11:48

标签: lambda java-8 java-stream

我需要比较映射A,映射B中存在的密钥。如果密钥同时存在于两个映射(A和B)中,则添加该特定密钥,并且需要使用lamda表达式将值添加到新映射c中。请在下面找到我的示例代码:

mapA.forEach((key, value) -> mapC.put(mapB.get(Key), value)));

以上代码当前未在添加到mapC之前检查mapA,mapB中是否存在密钥。

3 个答案:

答案 0 :(得分:8)

大致情况:

mapA
    .entrySet()
    .stream()
    .filter(entry -> mapB.containsKey(entry.getKey()))
    .collect(
        Collectors.toMap(Entry::getKey, Entry::getValue));

如果您不坚持使用lambda,那么您也可以这样做:

Map<K, V> mapC = new HashMap<>(mapA);
mapC.keySet().retainAll(mapB.keySet());

答案 1 :(得分:0)

您可以使用流和过滤器获取两个地图上都存在的键,然后迭代经过过滤的结果集以将其存储在第三张地图上。

    Map<Integer, String> mapA = new HashMap();
    Map<Integer, String> mapB =  new HashMap();
    Map<Integer, String> mapC =  new HashMap();

    mapA.put(1, "Hi");
    mapA.put(2, "Hello");
    mapB.put(1, "Hi");
    mapB.put(3, "Bye");

    mapA.entrySet().stream().filter(x -> mapB.containsKey(x.getKey())).forEach(x -> mapC.put(x.getKey(), x.getValue()));

    System.out.println(mapC); // output will be {1=Hi}

答案 2 :(得分:-1)

只需添加一个if条件,以检查第二张地图中是否存在该键。

mapA.forEach((key, value) -> {
    if (mapB.containsKey(key)) {
        mapC.put(mapB.get(key), value));
    }
});

但是,如果值不同怎么办?用你所说的,看来他们将是平等的

这里还有另外一种方法(假设它是Map<String, String进行演示)

Set<Map.Entry<String, String>> entrySetMapA = new HashSet<>(mapA.entrySet());
entrySetMapA.retainAll(mapB.entrySet());
entrySetMapA.forEach(entry -> mapC.put(entry.getKey(), entry.getValue()));
相关问题