List<Map<String,Object>> 按 key 进行分组,多场景

直接沾上代码

public class StreamTest {
    public static void main(String[] args) {
        List<Map<String,Object>> list = new ArrayList<>();
        Map<String,Object> m1 = new HashMap<>();
        m1.put("age","18");
        m1.put("name","小米");
        Map<String,Object> m2 = new HashMap<>();
        m2.put("age","18");
        m2.put("name","小兰");
        Map<String,Object> m3 = new HashMap<>();
        m3.put("age","19");
        m3.put("name","小明");
        Map<String,Object> m4 = new HashMap<>();
        m4.put("age","19");
        m4.put("name","小明");
        Map<String,Object> m5 = new HashMap<>();
        m5.put("age","20");
        m5.put("name","小刚");
        Map<String,Object> m6 = new HashMap<>();
        m6.put("age","20");
        m6.put("name","大头");
        Map<String,Object> m7 = new HashMap<>();
        m7.put("age","19");
        m7.put("name","小鸡");
        list.add(m1);
        list.add(m2);
        list.add(m3);
        list.add(m4);
        list.add(m5);
        list.add(m6);
        list.add(m7);
        //需求1:根据map 的key  进行分组,并返回分组后的 对应的value 值 用字符串拼接
        List<StringBuilder> collect1 = list.stream().collect(Collectors.groupingBy(x -> x.get("age"))).values().stream().map(d -> {
            StringBuilder sb = new StringBuilder();
            sb.append(d.stream().map(s -> String.valueOf(s.get("name"))).collect(Collectors.joining(",")));
            return sb;
        }).collect(Collectors.toList());

        for(int i = 0;i<collect.size();i++){
            System.out.println(collect1.get(i));
        }
        //打印结果:
        //小米,小兰
        //小明,小明,小鸡
        //小刚,大头
        
        //需求2:根据map的key 进行分组,并返回一个以分组后的key 为 key,value 为 value拼接的逗号分隔的字符串。 
        List<Map<String,String>> collect2 = list.stream().collect(Collectors.groupingBy(x -> String.valueOf(x.get("age")))).values()
                .stream().map(d -> {
            Map<String, String> mm = new HashMap<>();
            mm.put(String.valueOf(d.get(0).get("age")),
                    d.stream().map(dd -> String.valueOf(dd.get("name"))).collect(Collectors.joining(",")));
            return mm;
        }).collect(Collectors.toList());
        System.out.println(collect2);
        //打印结果
        //{18=小米,小兰}
        //{19=小明,小明,小鸡}
        //{20=小刚,大头}
    }
}

你可能感兴趣的:(stream,流,java)