java8 stream List<Map> is grouped according to the key of the map, and the result is converted into a list

Original business scenario: The data queried from the database is in List<Map> format, and then needs to be summarized according to one of the fields, and only another field is needed for the summary result. The following is the simulated data test

Code example:

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

        Map<String,Object> map=new HashMap<>();
        map.put("aaa","111");
        map.put("bbb","111");
        list.add(map);

        Map<String,Object> map2=new HashMap<>();
        map2.put("aaa","222");
        map2.put("bbb","222");
        list.add(map2);

        Map<String,Object> map3=new HashMap<>();
        map3.put("aaa","333");
        map3.put("bbb","333");
        list.add(map3);

        Map<String,List<String>> result=list.stream()
                .collect(
                        Collectors.groupingBy(
                                e->(((HashMap)e).get("aaa")).toString(),
                                Collectors.mapping(e->((HashMap)e).get("bbb").toString(),Collectors.toList())
                        ));
        System.out.println(JSONObject.toJSONString(result));

Output result:

{"111":["111"],"222":["222"],"333":["333"]}

Guess you like

Origin blog.csdn.net/caicai250/article/details/123506966