• Stream流最佳实战


    Stream流最佳实战

    stream 进行排序、分组、多级分组、交集、并集、差集等

    package com.al.admin.utils;
     
    import cn.hutool.core.util.ObjectUtil;
    import lombok.Data;
    import org.springframework.util.StringUtils;
     
    import java.text.SimpleDateFormat;
    import java.util.*;
    import java.util.function.Function;
    import java.util.function.Predicate;
    import java.util.stream.Collectors;
     
    /**
     * 测试
     */
    public class StreamUtil {
     
        public static void main(String[] args) {
     
            List<Student> students = new ArrayList<>();
            for(int i=0; i<5 ;i++) {
                Student student = new StreamUtil().new Student();
                student.setId(i+"");
                if(i > 2) {
                    student.setAge(1);
                } else {
                    student.setAge(2);
                }
                if(i > 3) {
                    student.setName("zhangsan");
                } else if(i == 0) {
                    student.setName(null);
                } else {
                    student.setName("lisi");
                }
                student.setMoney(i);
                student.setCreatedDate(null);
                students.add(student);
            }
    //多级进行分组 当然也可以进行其他的操作
            Map<String, Map<Integer, List<Student>>> collectq = students.stream()
                    .collect(Collectors.groupingBy(x -> StringUtils.isEmpty(x.getName()) ? "" : x.getName(), Collectors.groupingBy(Student::getAge)));
            System.out.println("collectq:" + collectq);
     
            SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd");
            Map<String, List<Student>> groupBy = students.stream().collect(Collectors.groupingBy(a -> sm.format(a.getCreatedDate())));
            System.out.println("==============");
            System.out.println(groupBy);
    
            /**
             * 条件过滤
             */
            System.out.println("条件过滤==============");
            System.out.println("student.getAge() >1 ==============");
            List<Student> collect = students.stream().filter(student -> student.getAge() > -1).collect(Collectors.toList());
            System.out.println(collect);
     
            /**
             * 正序排列
             */
            System.out.println("正序排列==============");
            collect = collect.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
            System.out.println(collect);
     
            /**
             * 倒序排列
             */
            System.out.println("倒序排列==============");
            collect = collect.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());
            System.out.println(collect);
     
            /**
             * string 类型的字段 倒序排列
             */
            System.out.println("string 类型的字段进行倒序排序 ==============");
            collect = collect.stream().sorted(Comparator.comparing(Student::getId).reversed()).collect(Collectors.toList());
            System.out.println(collect);
     
     
            /**
             * string 类型的字段 进行截取 倒序排列
             */
            System.out.println("string 类型的字段进行倒序排序 ==============");
            collect = collect.stream().sorted((o1,o2) -> {
                try {
                    return Integer.parseInt(o2.getName().split("-")[1].substring(0,5)) - Integer.parseInt(o1.getName().split("-")[1].substring(0,5));
                } catch (Exception e){
                    e.printStackTrace();
                }
                return 0;
            }).collect(Collectors.toList());
            System.out.println(collect);
     
     
            /**
             * 多字段倒序排序
             */
            System.out.println("多字段倒序排序 ==============");
            collect = collect.stream().sorted(Comparator.comparing(Student::getAge).thenComparing(Student::getId).reversed()).collect(Collectors.toList());
            System.out.println(collect);
     
            /**
             * 多字段条件
             */
            System.out.println("age大于20 money大于3000的数据==============");
            Predicate<Student> predicate1 = student -> student.getAge()>20;
            Predicate<Student> predicate2 = student -> student.getMoney()>3000;
            List<Student> collect1 = collect.stream().filter(predicate1.and(predicate2)).collect(Collectors.toList());
            System.out.println(collect1);
     
            /**
             * 两个集合差集 、 并集 、 交集
             * 集合 students 、 collect
             */
            System.out.println("两个集合差集");
            Predicate<Student> predicate =
                    user -> collect1.stream()
                            .noneMatch(user1 -> (user.getId()).equalsIgnoreCase(user1.getId()));
            collect = students.stream().filter(predicate).collect(Collectors.toList());
            System.out.println("students - collect1的差集  注意 集合a对集合b之间的差集 和 集合b对集合a之间的差集 不一样");
            System.out.println(collect);
     
            System.out.println("两个集合交集");
            Predicate<Student> predicate3 =
                    user -> collect1.stream()
                            .anyMatch(user1 -> (user.getId()).equalsIgnoreCase(user1.getId()));
            collect = students.stream().filter(predicate3).collect(Collectors.toList());
            System.out.println("students - collect1的交集");
            System.out.println(collect);
     
            System.out.println("两个集合并集");
            List<Student> collect2 = students.parallelStream().collect(Collectors.toList());
            List<Student> collect3 = collect1.parallelStream().collect(Collectors.toList());
            collect2.addAll(collect3);
            List<Student> collect4 = collect2.stream().distinct().collect(Collectors.toList());
            System.out.println(collect4);
     
            System.out.println("list 转 map");
            System.out.println("key是list对象中id,value是list对象中的年龄");
            Map<String, Integer> map = students.stream().collect(Collectors.toMap(Student::getId, Student::getAge));
            System.out.println(map);
     
            System.out.println("key是list对象中id,value是list对象");
            Map<String, Student> map1 = students.stream().collect(Collectors.toMap(Student::getId, student -> student));
            System.out.println(map1);
            System.out.println("key是list对象中id,value是list对象 另一种写法");
            Map<String, Student> map2 = students.stream().collect(Collectors.toMap(Student::getId, Function.identity()));
            System.out.println(map2);
     
            System.out.println("key是对象中的某个属性值,value是对象本身,当key冲突时选择第二个key值覆盖第一个key值。");
            Map<String, Student> map3 = students.stream().collect(Collectors.toMap(Student::getId, Function.identity(), (oldValue, newValue) -> newValue));
            System.out.println(map3);
     
            System.out.println("map 转 list");
            List<String> collect5 = map3.keySet().stream().collect(Collectors.toList());
            List<Student> collect6 = map3.values().stream().collect(Collectors.toList());
            System.out.println("map的key转list::"+collect5);
            System.out.println("map的value转list::"+collect6);
     
     
            List<Student> lst = map.entrySet().stream().map(c -> {
                Student student = new StreamUtil().new Student();
                student.setId(c.getKey());
                student.setAge(c.getValue());
                return student;
            }).collect(Collectors.toList());
            System.out.println("通过map的key,value转对象集合");
            System.out.println(lst);
     
        }
     
        @Data
        public class Student {
     
            private String id;
            private int age;
            private double money;
            private String name;
            private Date createdDate;
     
            public Student(){
     
            }
        }
     
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186

    2、
    java中用stream进行去重,排序,分组

    
    
    • 1

    3、stream排序

        public void test6() {
            List<User> list = new ArrayList<>();
            //定义三个用户对象
            User user1 = new User();
            user1.setUserName("admin");
            user1.setAge(16);
            user1.setSex("男");
            User user2 = new User();
            user2.setUserName("root");
            user2.setAge(20);
            user2.setSex("女");
            User user3 = new User();
            user3.setUserName("admin");
            user3.setAge(18);
            user3.setSex("男");
            User user4 = new User();
            user4.setUserName("admin11");
            user4.setAge(22);
            user4.setSex("女");
            System.out.println(list);
            // 年龄排序(逆序)
            List<User> collect = list.stream().sorted(Comparator.comparing(User::getAge).reversed()).collect(Collectors.toList());
            System.out.println(collect);
            // 写法2
            List<User> collect1 = list.stream().sorted(Comparator.comparing(User::getAge, Comparator.reverseOrder())).
                    collect(Collectors.toList());
            System.out.println(collect1);
            // lambda表达式
            List<User> collect2 = list.stream().sorted((a, b) -> b.getAge() - a.getAge()).collect(Collectors.toList());
            System.out.println(collect2);
            // 并行排序 - 排序数量大时使用并行排序,提高排序速度
            list.parallelStream().sorted().collect(Collectors.toList());
            // 多字段排序1-都进行倒序排序(先根据年龄倒序,再根据用户名倒序)
            List<User> collect3 = list.stream().sorted(Comparator.comparing(User::getAge).
                    thenComparing(User::getUserName).reversed()).collect(Collectors.toList());
            System.out.println(collect3);
            // 多字段排序2-先根据年龄逆序,再根据用户名顺序--reversed()是让他前面所有字段进行倒序
            list.stream().sorted(Comparator.comparing(User::getAge).reversed().
                    thenComparing(User::getUserName)).collect(Collectors.toList());
            // 多字段排序3
            list.stream().sorted(Comparator.comparing(User::getAge, Comparator.reverseOrder()).
                    thenComparing(User::getUserName, Comparator.reverseOrder())).collect(Collectors.toList());
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43

    分组

    stream流——分组
    Stream流分组

  • 相关阅读:
    高并发笔记
    基于SSM的校园资讯推荐系统设计与实现
    Oracle 数据库用户创建、重启、导入导出
    fuzz——AFL基础使用方法
    web前端期末大作业 html+css+javascript火影忍者网页设计实例 动漫网站制作
    DRF的Serializer组件(源码分析)
    微信小程序-微信授权登录
    白嫖游戏指南,Epic喜加二:《INDUSTRIA》《LISA: Definitive Edition》
    ETL:数据转换与集成的关键过程
    网络安全——SQL报错注入
  • 原文地址:https://blog.csdn.net/m0_46393656/article/details/133673734