我一直试图理解为什么在收集 map 时不会触发重复键功能,但没有成功。我正在使用 Java SE 8 [1.8.0_141]。
public static void main(String[] args) {
Map<Long, Long> ts1 = new HashMap<Long, Long>();
Map<Long, Long> ts2 = new HashMap<Long, Long>();
ts1.put(0L, 2L);
ts1.put(1L, 7L);
ts2.put(2L, 2L);
ts2.put(2L, 3L);
Map<Long, Long> mergedMap = Stream.of(ts1, ts2)
.flatMap(map -> map.entrySet().stream())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(v1, v2) -> {
System.out.println("Duplicate found");
return v1 + v2;}
));
mergedMap.entrySet().stream().forEach(e -> System.out.println(e.getKey() + " " + e.getValue()));
}
结果是
0 2
1 7
2 3
我期待着
0 2
1 7
2 5
最佳答案
当你这样做时:
ts2.put(2L, 2L);
ts2.put(2L, 3L);
第二个 put
会覆盖第一个。因此,ts2
映射仅包含一项:最后一项:(2L, 3L)
。
那么,就没有什么可以合并的了。
关于java - 忽略合并映射中的重复键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59616910/