地图流到地图 [英] Stream of maps to map
本文介绍了地图流到地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Java 8中,如何将Map
(相同类型)的Stream
展平为单个Map
?
How can I flatten a Stream
of Map
s (of the same types) to a single Map
in Java 8?
Map<String, Long> toMap(Stream<Map<String, Long>> stream) {
return stream. ???
}
推荐答案
我的语法可能有些偏离,但是flatMap应该为您完成大部分工作:
My syntax may be a bit off, but flatMap should do most of the work for you :
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
}
这篇关于地图流到地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文