Dariusz Mydlarz
Dariusz Mydlarz

Reputation: 3002

Stream of maps to map

How can I flatten a Stream of Maps (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

Answers (2)

Brujua
Brujua

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

Eran
Eran

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

Related Questions