Lambda 使用lamda表达式java比较两个映射
我需要比较映射A和映射B中存在的键。如果两个映射(A和B)中都存在该键,则需要使用lamda表达式将该特定键和值添加到新映射c中。请在下面找到我的示例代码:Lambda 使用lamda表达式java比较两个映射,lambda,java-8,java-stream,Lambda,Java 8,Java Stream,我需要比较映射A和映射B中存在的键。如果两个映射(A和B)中都存在该键,则需要使用lamda表达式将该特定键和值添加到新映射c中。请在下面找到我的示例代码: mapA.forEach((key, value) -> mapC.put(mapB.get(Key), value))); 在添加到mapC之前,上述代码当前不会检查mapA、mapB中是否存在密钥。只需添加一个if条件,以检查第二个地图中是否存在密钥 mapA.forEach((key, value) -> { i
mapA.forEach((key, value) -> mapC.put(mapB.get(Key), value)));
在添加到mapC之前,上述代码当前不会检查mapA、mapB中是否存在密钥。只需添加一个
if
条件,以检查第二个地图中是否存在密钥
mapA.forEach((key, value) -> {
if (mapB.containsKey(key)) {
mapC.put(mapB.get(key), value));
}
});
但如果价值观不同呢?照你所说的,他们似乎是平等的
这里还有一种方法(假设它是映射mapC.put(entry.getKey(),entry.getValue());
大致如下:
mapA
.entrySet()
.stream()
.filter(entry -> mapB.containsKey(entry.getKey()))
.collect(
Collectors.toMap(Entry::getKey, Entry::getValue));
如果您不坚持lambdas,那么您也可以:
Map<K, V> mapC = new HashMap<>(mapA);
mapC.keySet().retainAll(mapB.keySet());
mapmap=newhashmap(mapA);
mapC.keySet().retainal(mapB.keySet());
您可以使用stream和filter获取两个映射上存在的键,然后迭代过滤后的结果集,将其存储在第三个映射上
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}
Map mapA=newhashmap();
Map mapB=新的HashMap();
Map mapC=新的HashMap();
mapA.put(1,“Hi”);
mapA.put(2,“你好”);
mapB.put(1,“Hi”);
mapB.put(3,“再见”);
mapA.entrySet().stream().filter(x->mapB.containsKey(x.getKey()).forEach(x->mapC.put(x.getKey(),x.getValue());
System.out.println(mapC);//输出将为{1=Hi}
您在检查部分的尝试是什么?如果下面的一个答案解决了您的问题,您应该接受它(单击相应答案旁边的复选标记)。这有两件事。它让每个人都知道你的问题已经解决到令你满意的程度,并让帮助你的人相信你的帮助。这不是真正正确的Java8流样式。基本上,您只是将for循环替换为forEach
,就这样。查看filter
以检查一些谓词,并查看collect
以某种结构收集结果。在我看来,这太“程序化”了。在使用lambdas时,尝试采用更具功能性的方法(这就是为什么首先引入lambdas的原因)。
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}