Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert list of map to map using flatMap

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.

like image 241
math Avatar asked Oct 26 '17 22:10

math


1 Answers

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));
like image 200
VHS Avatar answered Sep 17 '22 14:09

VHS