问题
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. ???
}
回答1:
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
}
来源:https://stackoverflow.com/questions/26752919/stream-of-maps-to-map