Bootstrap

Collectors.groupingBy实战

前言

    Collectors.groupingBy()是Java8的新特性,在日常开发中也是比较常用的。根据某些条件进行分组,分组统计,将List转换为map等等。在Java8的源码里面,Collectors.groupingBy()也有几个重载的方法,可以去探究探究。

实体类

@Data
public class CustTag {
    private Long id;
    private Integer num;
    private String name;
    private String category;

    public CustTag(Long id, Integer num, String name, String category) {
        this.id = id;
        this.num = num;
        this.name = name;
        this.category = category;
    }

}

分组1(条件在实体类)

    public static void main(String[] args) {
        CustTag custTag1 = new CustTag(1L, 1, "1年", "普通");
        CustTag custTag2 = new CustTag(2L, 3, "半年", "普通");
        CustTag custTag3 = new CustTag(3L, 1, "3个月", "VIP");
        CustTag custTag4 = new CustTag(4L, 4, "1个月", "VIP");
        CustTag custTag5 = new CustTag(5L, 5, "天天", "GVP");
        List<CustTag> custTagList = Lists.newArrayList(custTag1, custTag2, custTag3, custTag4, custTag5);

        Map<String, List<CustTag>> custTagMap = custTagList.stream()
                .collect(Collectors.groupingBy(CustTag::getCategory));
        custTagMap.forEach((category, custTag) -> {
            log.info("custTag>>>>>>>>>>>>>>>>>>>>【{}】-【{}】", category, custTag);
        });
    }

按照实体类属性category分组打印结果

 分组2(条件在实体类,key自己额外定义)

    public static void main(String[] args) {
        CustTag custTag1 = new CustTag(1L, 1, "1年", "普通");
        CustTag custTag2 = new CustTag(2L, 3, "半年", "普通");
        CustTag custTag3 = new CustTag(3L, 1, "3个月", "VIP");
        CustTag custTag4 = new CustTag(4L, 4, "1个月", "VIP");
        CustTag custTag5 = new CustTag(5L, 5, "天天", "GVP");
        List<CustTag> custTagList = Lists.newArrayList(custTag1, custTag2, custTag3, custTag4, custTag5);

    Map<String, List<CustTag>> custTagMap = custTagList.stream()
            .collect(Collectors.groupingBy(s -> {
                if (s.num == 1) {
                    return "R1";
                }
                if (s.num == 3) {
                    return "R2";
                }
                if (s.num == 4) {
                    return "R3";
                }
                return "R4";
            }));

        custTagMap.forEach((Ri, custTag) -> {
        log.info("custTag>>>>>>>>>>>>>>>>>>>>【{}】-【{}】", Ri, custTag);
    });

按照实体类属性num分组,但是key自己定义打印结果

;