Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. ??? } 
like image 967
Dariusz Mydlarz Avatar asked Nov 05 '14 08:11

Dariusz Mydlarz


People also ask

How can I merge two maps?

The merge() function takes 3 arguments: key, value and a user-provided BiFunction to merge values for duplicate keys. In our example, we want to append the values (from both maps) for a duplicate key. //map 1 HashMap<Integer, String> firstMap = new HashMap<>(); firstMap. put(1, "A"); firstMap.

How does stream map work?

Stream map(Function mapper) returns a stream consisting of the results of applying the given function to the elements of this stream. Stream map(Function mapper) is an intermediate operation. These operations are always lazy.

What is flatMap?

flatMap() The flatMap() method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a map() followed by a flat() of depth 1 ( arr. map(... args).


1 Answers

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 } 
like image 55
Eran Avatar answered Sep 21 '22 18:09

Eran