java8 stream 用法 分组 排序 筛选 聚合 统计 求平均 最大 最小 max sum

实现Mysql 分组 统计 排序 的效果

 public static void oooo() {
        User user1 = new User("zhangsan", "beijing", 10);
        User user2 = new User("zhangsan", "beijing", 20);
        User user3 = new User("lisi", "shanghai", 5);
        List<User> list = new ArrayList<User>();
        list.add(user1);
        list.add(user2);
        list.add(user3);
        //多字段分组
        Map<String, List<User>> collect = list.stream().collect(
                Collectors.groupingBy(user -> { return user.getName() + "#" + user.getAddress(); })
        );

        List<User> data = new ArrayList<>();
        //统计
        collect.entrySet().stream().forEach(ety -> {
            User xx = ety.getValue().stream().reduce((x, y) -> {
                User user = new User();
                user.setAddress(x.getAddress());
                user.setName(x.getName());
                user.setAge(x.getAge() + y.getAge());
                return user;
            }).get();
            data.add(xx);
        });

        //排序
        List<User> data2 = data.stream().sorted(Comparator.comparing(User::getAge)).collect(Collectors.toList());
        System.out.println(collect);
    }

多个字段分组

连接字段的方式

   public static void oooo() {
        User user1 = new User("zhangsan", "beijing", 10);
        User user2 = new User("zhangsan", "beijing", 20);
        User user3 = new User("lisi", "shanghai", 30);
        List<User> list = new ArrayList<User>();
        list.add(user1);
        list.add(user2);
        list.add(user3);
        Map<String, List<User>> collect = list.stream().collect(Collectors.groupingBy(e -> fetchGroupKey(e)));
        System.out.println(collect);
    }
    private static String fetchGroupKey(User user){
        return user.getName() +"#"+ user.getAddress();
    }

原语方式

Map<String,Map<String, Map<String, List<Student>>>> result = students.stream().collect(
                    Collectors.groupingBy(Student::getGrade,
                        Collectors.groupingBy(Student::getClass,
                            Collectors.groupingBy(Student::getTeacher)))
);

java 8 stream
https://blog.csdn.net/zhouzhiwengang/article/details/112319054
https://blog.csdn.net/weixin_30249203/article/details/99397267
https://www.cnblogs.com/JourneyOfFlower/p/15699236.html
https://blog.csdn.net/qq_43410878/article/details/123716629

posted @ 2022-08-15 18:31  方东信  阅读(957)  评论(0编辑  收藏  举报