如何在 Java 8 中将 Map
(相同类型)的 Stream
扁平化为单个 Map
?
Map<String, Long> toMap(Stream<Map<String, Long>> stream) {
return stream. ???
}
最佳答案
我的语法可能有点偏离,但 flatMap 应该为您完成大部分工作:
Map<String, Long> toMap(Stream<Map<String, Long>> stream) {
return stream.flatMap (map -> map.entrySet().stream()) // this would create a flattened
// Stream of all the map entries
.collect(Collectors.toMap(e -> e.getKey(),
e -> e.getValue())); // this should collect
// them to a single map
}
关于java - map 流到 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62119189/