忽略合并映射中的重复键



我一直在试图理解为什么在收集地图时没有触发重复键功能,但没有运气。我正在使用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)

所以,没有什么可以合并的。

最新更新