Reputation: 3002
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. ???
}
Upvotes: 48
Views: 65148
Reputation: 91
I would like to propose a solution using reduce(), which is more intuitive for me. I would use it inline though.
Map<String, Long> toMap(Stream<Map<String, Long>> stream) {
return stream.reduce(new HashMap<>(), Util::reduceInto);
}
And in Util.java:
public static <R, T> Map<R, T> reduceInto(Map<R, T> into, Map<R, T> valuesToAdd) {
reduceInto.putAll(valuesToAdd);
return reduceInto;
}
In this case reduceInto() works for any type of map and uses mutability to avoid creating a new Map for each item of the Stream.
Important: although this method allows repeated keys in the stream, reduceInto() is not associative, meaning that if you have repeated keys there is no guarantee of which will be the final value.
Upvotes: 2
Reputation: 393831
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
}
Upvotes: 72