JDK8对List分组操作(stream的groupby)

时间:2024-11-09 14:15:08

数据准备

public class TestGroupBy {

    public static List<User> users = getPeoples();
      
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    static class User {
        private Integer id;
        private Integer schoolId;
        private String username;
        private String edu;
        private Double price;
    }

    private static List<User> getPeoples(){
        return (
                new User(1001,100,"小1","001",0.01),
                new User(1002,100,"小2","002",0.2),
                new User(2010,200,"小3","001",3.0),
                new User(3001,300,"小4","001",40.0)
        );
    }
}

group by的重载方法

group by生成一个拥有分组功能的Collector,有三个重载方法。

1.一个参数

按照该参数进行分组。返回一个Map集合,每个Map的key默认是分组参数的类型,value是一个List集合 (注意:Map中key的类型要与参数类型一致)

public void test1() {
    Map<String,List<User >> collect = ().collect((User::getEdu));
}

2.两个参数

延续"一个参数",第二个参数用来处理"一个参数"获得结果(value)的数据

2.1对结果进行映射

public void test2() {
    Map<String,List<Integer>> collect = ().collect((User::getEdu,
    //第二个参数对Map的value进行处理(映射)
    (User::getId, ())));
}

2.2对结果进行求和

public static void test3() {
    Map<String,Double> collect = ().collect((User::getEdu,
    //对参数进行累计求和
    (User::getPrice)));
    (collect);
}

2.3对结果的统计

public static void test4() {
    Map<String,Long> collect = ().collect((User::getEdu,
    //获取count数量
    ()));
    (collect);
}

3.三个参数

第三个参数添加了对结果Map的生成方式,默认是HashMap

public static void test3() {
    Map<String,Double> collect = ().collect((User::getEdu,
    //决定map的生成方式,使用TreeMap
    TreeMap::new,
    //对参数进行累计求和
    (User::getPrice)));
    (collect);
}

文献参考小胖学编程