convert list of map to map using flatMap

前端 未结 3 1621
执笔经年
执笔经年 2021-01-06 09:39

How I can merge List> to Map using flatMap?

Here\'s what I\'ve tried:

3条回答
  •  独厮守ぢ
    2021-01-06 10:01

    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.

提交回复
热议问题