How I can merge List
to Map
using flatMap
?
Here\'s what I\'ve tried:
A very simple way would be to just use putAll
:
Map result = new HashMap<>();
response.forEach(result::putAll);
If you particularly want to do this in a single stream operation then use a reduction:
response.stream().reduce(HashMap::new, Map::putAll);
Or if you really want to use flatMap
:
response.stream().map(Map::entrySet).flatMap(Set::stream)
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue, Map::putAll));
Note the merging function in the final alternative.