convert list of map to map using flatMap

math picture math · Oct 27, 2017 · Viewed 8k times · Source

How I can merge List<Map<String,String>> to Map<String,String> using flatMap?

Here's what I've tried:

final Map<String, String> result = response
    .stream()
    .collect(Collectors.toMap(
        s -> (String) s.get("key"),
        s -> (String) s.get("value")));
result
    .entrySet()
    .forEach(e -> System.out.println(e.getKey() + " -> " + e.getValue()));

This does not work.

Answer

VHS picture VHS · Oct 27, 2017

Assuming that there are no conflicting keys in the maps contained in your list, try following:

Map<String, String> maps = list.stream()
    .flatMap(map -> map.entrySet().stream())
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));