Convert List of Maps to single Map via streams

后端 未结 4 1247
时光取名叫无心
时光取名叫无心 2020-12-06 03:00

I query the DB for two columns where the first one is the key to the second one. How can I convert the resulting list to a single map? Is it even possible? I have just seen

4条回答
  •  感情败类
    2020-12-06 03:24

    The problem is you have a list of maps. The code below should work:

    Map result = new HashMap<>();
    steps.stream().forEach(map -> {
        result.putAll(map.entrySet().stream()
            .collect(Collectors.toMap(entry -> entry.getKey(), entry -> (String) entry.getValue())));
    });
    

    If we try to run this example

    Map steps1 = new HashMap<>();
    steps1.put("key11", "value11");
    steps1.put("key12", "value12");
    
    Map steps2 = new HashMap<>();
    steps2.put("key21", "value21");
    steps2.put("key22", "value22");
    
    List> steps = new ArrayList<>();
    steps.add(steps1);
    steps.add(steps2);
    
    Map result = new HashMap<>();
    steps.stream().forEach(map -> {
        result.putAll(map.entrySet().stream()
            .collect(Collectors.toMap(entry -> entry.getKey(), entry -> (String) entry.getValue())));
    });
    System.out.println(result);
    

    It happily gives us the output like that:

    {key12=value12, key11=value11, key22=value22, key21=value21}
    

提交回复
热议问题