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. ??? }
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.
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.
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).
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With