Java 8 - List<Map> into Single Map

Shan :

I have a List<Map<String, String>>. I would like to convert it into single map.

The list size can be 1..n. Not sure how to do that using Java 8 Stream?

List<Map<String, String>> mapList = new ArrayList<>();

Map<String, String> map1 = new HashMap<>();
map1.put("1", "One");
map1.put("2", "Two");

Map<String, String> map2 = new HashMap<>();
map2.put("3", "Three");
map2.put("4", "Four");

mapList.add(map1);
mapList.add(map2);

Map<String, String> finalMap = new HashMap<>();

We could do something like this in Java 7:

for(Map<String, String> map : mapList) {            
    for(String key : map.keySet()) {                
        finalMap.put(key, map.get(key));
    }           
}

System.out.println("Final Map " + finalMap); // Final Map {1=One, 2=Two, 3=Three, 4=Four}
Andronicus :

You can flatMap it and then use Collectors.toMap:

mapList.stream()
    .flatMap(m -> m.entrySet().stream())
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

Note, that duplicate keys are not handled. To ignore duplicates, you can use:

Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (v1, v2) -> v1)

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=478022&siteId=1