convert list of map to map using flatMap

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

How I can merge List> to Map using flatMap?

Here\'s what I\'ve tried:

相关标签:
3条回答
  • 2021-01-06 09:54

    If you're ok with overriding the keys, you can just merge the Maps into a single map with collect, even without flatMaps:

    public static void main(String[] args) throws Exception {
        final List<Map<String, String>> cavia = new ArrayList<Map<String, String>>() {{
            add(new HashMap<String, String>() {{
                put("key1", "value1");
                put("key2", "value2");
                put("key3", "value3");
                put("key4", "value4");
            }});
            add(new HashMap<String, String>() {{
                put("key5", "value5");
                put("key6", "value6");
                put("key7", "value7");
                put("key8", "value8");
            }});
            add(new HashMap<String, String>() {{
                put("key1", "value1!");
                put("key5", "value5!");
            }});
        }};
    
        cavia
                .stream()
                .collect(HashMap::new, HashMap::putAll, HashMap::putAll)
                .entrySet()
                .forEach(System.out::println);
    }
    

    Will output:

    key1=value1!
    key2=value2
    key5=value5!
    key6=value6
    key3=value3
    key4=value4
    key7=value7
    key8=value8
    
    0 讨论(0)
  • 2021-01-06 09:59

    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));
    
    0 讨论(0)
  • 2021-01-06 10:01

    A very simple way would be to just use putAll:

    Map<String, String> 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<String, String>::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.

    0 讨论(0)
提交回复
热议问题