• java8 lambda常用方法汇总


    java8 lambda常用方法汇总

    在日常工作中,经常会用到 java8 的 lambda 新特性,可以让代码变得简洁,便于理解,并减少代码量,本文主要列举常用的 lambda 方法,主要涉及:forEach、collect、map、reduce、flatMap、peek、distinct、sorted、filter、allMatch、anyMatch、findFirst、Optional。

    动动发财小手,关注 + 点赞 + 收藏不迷路。

    一、lambda demo

    lambda示例代码如下:

    package utils;
    
    import lombok.AllArgsConstructor;
    import lombok.Builder;
    import lombok.Data;
    
    import java.util.Arrays;
    import java.util.Comparator;
    import java.util.List;
    import java.util.Optional;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    import static com.google.common.collect.Lists.newArrayList;
    
    /**
     * java8 lambda常用方法汇总
     *
     * @Author: tinker
     * @Date: 2022/02/09 17:21
     */
    public class LambdaDemo {
    
        public static void main(String[] args) {
            // 1.forEach(替代for循环)
            forEach();
    
            // 2.collect(实现list中对象转换)
            collect();
    
            // 3.reduce
            reduce();
    
            // 4.map
            map();
    
            // 5.peek
            peek();
    
            // 6.distinct去重
            distinct();
    
            // 7.sorted排序(正序 -> Comparator.naturalOrder() 逆序 -> Comparator.reverseOrder())
            sorted();
    
            // 8.filter
            filter();
    
            // 9.allMatch(所有的都要满足)
            allMatch();
    
            // 10.anyMatch(所有的都要满足)
            anyMatch();
    
            // 11.findFirst
            findFirst();
    
            // 12.Optional
            optional();
    
            // 13.flatMap
            flatMap();
        }
    
        public static void forEach() {
            List<Integer> list1 = Arrays.asList(1, 2, 3);
            // before
            for (Integer val : list1) {
                System.out.print(val + " ");
            }
    
            // after
            list1.forEach(val -> System.out.print(val + " "));
            System.out.println();
            System.out.println();
        }
    
        public static void collect() {
            // before
            User user1 = new User(1L, "Tom");
            User user2 = new User(2L, "Jack");
            List<User> userList = Arrays.asList(user1, user2);
            List<Person> personList1 = newArrayList();
            for (User user : userList) {
                Person person = new Person(user.getUserId(), user.getUserName());
                personList1.add(person);
            }
            System.out.println(personList1.toString());
    
            // after
            List<Person> personList2 = userList.stream().map(LambdaDemo::user2Person).collect(Collectors.toList());
            System.out.println(personList2.toString());
            System.out.println();
        }
    
        @Data
        @AllArgsConstructor
        public static final class User {
    
            User(Long userId, String userName) {
                this.userId = userId;
                this.userName = userName;
            }
    
            User(Long userId, String userName, String school) {
                this.userId = userId;
                this.userName = userName;
                this.school = school;
            }
    
            private Long userId;
            private String userName;
            private int age;
            private String school;
        }
    
        @Builder
        @Data
        @AllArgsConstructor
        public static final class Person {
            private Long personId;
            private String personName;
        }
    
        public static Person user2Person(User user) {
            return Person.builder()
                    .personId(user.getUserId())
                    .personName(user.getUserName())
                    .build();
        }
    
        public static void reduce() {
            // 一个参数的reduce
            reduce1();
            // 两个参数的reduce
            reduce2();
            // 三个参数的reduce
            reduce3();
        }
    
        /**
         * 一个参数的reduce:将 list1 中的value相加
         */
        public static void reduce1() {
            List<Integer> list1 = Arrays.asList(1, 2, 3);
            System.out.println("sum value should be 6, the reduce value is " + list1.stream().reduce((i, j) -> i + j).get());
        }
    
        /**
         * 两个参数的reduce:将 result 与 list1 中的value相加
         */
        public static void reduce2() {
            List<Integer> list1 = Arrays.asList(1, 2, 3);
            Integer result = 10;
            System.out.println("sum value should be 16, the reduce value is " + list1.stream().reduce(result, (i, j) -> i + j));
        }
    
        /**
         * 三个参数的reduce:将 identity 与 list1中的 value 相加, 之后再将结果相加
         */
        public static void reduce3() {
            List<Integer> list1 = Arrays.asList(1, 2, 3);
            Integer identity = 1;
            // (1 + 1) + (1 + 2) + (1 + 3) = 9
            System.out.println("sum value should be 9, the reduce value is " +
                    list1.parallelStream().reduce(identity, (i, j) -> i + j, (i, j) -> i + j));
    
            // (2 + 1) + (2 + 2) + (2 + 3) = 12
            identity = 2;
            System.out.println("sum value should be 12, the reduce value is " +
                    list1.parallelStream().reduce(identity, (i, j) -> i + j, (i, j) -> i + j));
            System.out.println();
        }
    
        public static void map() {
            List<String> list = Stream.of(
                    new User(1L, "Tom"),
                    new User(2L, "Jack"),
                    new User(3L, "Scott"))
                    .map(User::getUserName).collect(Collectors.toList());
            System.out.println(list);
            System.out.println();
        }
    
        /**
         * peek 主要被用来debug, 不会该表元素的value, 当元素为对象, 实际结果会改变
         */
        public static void peek() {
            System.out.println(">> peek() method官方文档显示, 主要被用来debug, 打印流水线中的元素value");
            Stream.of("one", "two", "three", "four")
                    .filter(e -> e.length() > 3)
                    .peek(e -> System.out.println("Filtered value: " + e))
                    .map(String::toUpperCase)
                    .peek(e -> System.out.println("Mapped value: " + e))
                    .collect(Collectors.toList());
    
            System.out.println(">> peek 不会讲元素转换成大写格式");
            Stream.of("one", "two", "three", "four")
                    .filter(e -> e.length() > 3)
                    .peek(String::toUpperCase)
                    .forEach(e -> System.out.print(e + " "));
            System.out.println();
    
            System.out.println(">> map 对比");
            Stream.of("one", "two", "three", "four")
                    .filter(e -> e.length() > 3)
                    .map(String::toUpperCase)
                    .forEach(e -> System.out.print(e + " "));
            System.out.println();
    
    
            System.out.println(">> 如果元素是对象, peek操作后, 实际的结果会改变");
            List<User> userList = Stream.of(
                    new User(1L, ""),
                    new User(2L, ""),
                    new User(3L, ""))
                    .peek(u -> u.setUserName("scott"))
                    .collect(Collectors.toList());
            System.out.println(userList);
    
            System.out.println();
        }
    
        public static void distinct() {
            List<Integer> list = Stream.of(1, 1, 1, 2, 2, 3).distinct().collect(Collectors.toList());
            System.out.println(list);
            System.out.println();
        }
    
        public static void sorted() {
            // 正序
            List<Integer> list1 = Stream.of(5, 3, 2, 4, 1)
                    .distinct()
                    .sorted(Comparator.naturalOrder())
                    // 也可以使用以下写法
    //                .sorted(((o1, o2) -> o1 - o2))
                    .collect(Collectors.toList());
            System.out.println(list1);
    
            // 逆序
            List<Integer> list2 = Stream.of(5, 3, 2, 4, 1)
                    .distinct()
                    .sorted(Comparator.reverseOrder())
                    // 也可以使用以下写法
    //                .sorted(((o1, o2) -> o2 - o1))
                    .collect(Collectors.toList());
            System.out.println(list2);
    
            // 只针对特定字段进行排序
            System.out.println(">> 针对 UserId进行排序, 写法一");
            List<User> userList1 = Arrays.asList(
                    new User(3L, "Scott"),
                    new User(1L, "Tom"),
                    new User(2L, "Jack"));
            userList1.sort((u1, u2) -> u1.userId.compareTo(u2.getUserId()));
            System.out.println(userList1);
    
            System.out.println(">> 针对 UserId进行排序, 写法二");
            List<User> userList2 = Arrays.asList(
                    new User(3L, "Scott"),
                    new User(1L, "Tom"),
                    new User(2L, "Jack"));
            // 错误示例:不会改变 userList2, 需要接收返回值
            userList2.stream().sorted(Comparator.comparing(User::getUserId));
            System.out.println(userList2);
    
            System.out.println(">> Comparator 写法不会改变 userList2, 需要接收返回值才可以");
            userList2 = Stream.of(
                    new User(3L, "Scott"),
                    new User(1L, "Tom"),
                    new User(2L, "Jack"))
                    .sorted(Comparator.comparing(User::getUserId))
                    // 逆序
    //                .sorted(Comparator.comparing(User::getUserId).reversed())
                    .collect(Collectors.toList());
            System.out.println(userList2);
    
            System.out.println(">> 多个字段排序");
            userList2 = Stream.of(
                    new User(3L, "Scott", "北京大学"),
                    new User(1L, "Tom", "北京大学"),
                    new User(2L, "Jack", "清华大学"))
                    .sorted(Comparator.comparing(User::getSchool).thenComparing(User::getUserId))
                    .collect(Collectors.toList());
            System.out.println(userList2);
    
            System.out.println();
        }
    
        /**
         * 过滤满足条件的元素
         */
        public static void filter() {
            List<Integer> list1 = Stream.of(5, 3, 2, 4, 1)
                    .filter(e -> e.compareTo(3) >= 0)
                    .sorted(Comparator.naturalOrder())
                    .collect(Collectors.toList());
            System.out.println("Filtered list should be [3, 4, 5], list1 = " + list1);
    
            System.out.println();
        }
    
        /**
         * 所有的都要满足
         */
        public static void allMatch() {
            boolean result = Stream.of(
                    new User(3L, "Scott", 23, "北京大学"),
                    new User(1L, "Tom", 21, "北京大学"),
                    new User(2L, "Jack", 22, "清华大学"))
                    .allMatch(e -> e.getAge() >= 20);
            System.out.println(result);
    
            System.out.println();
        }
    
        /**
         * 其中一个元素满足即可
         */
        public static void anyMatch() {
            boolean result = Stream.of(
                    new User(3L, "Scott", 18, "北京大学"),
                    new User(1L, "Tom", 21, "北京大学"),
                    new User(2L, "Jack", 17, "清华大学"))
                    .anyMatch(e -> e.getAge() >= 20);
            System.out.println(result);
    
            System.out.println();
        }
    
        /**
         * 返回找到的第一个元素
         */
        public static void findFirst() {
            Optional<User> userOpt = Stream.of(
                    new User(3L, "Scott", 23, "北京大学"),
                    new User(1L, "Tom", 21, "北京大学"),
                    new User(2L, "Jack", 22, "清华大学"))
                    .filter(e -> e.getAge() >= 20)
                    .sorted(Comparator.comparing(User::getUserId))
                    .findFirst();
            System.out.println(userOpt.get());
    
            System.out.println();
        }
    
        /**
         * 其中一个元素满足即可
         */
        public static void optional() {
            User user = null;
            String userName = Optional.ofNullable(user).map(User::getUserName).orElse("default name");
            System.out.println(userName);
    
            user = new User(1L, "Tom", 21, "北京大学");
            userName = Optional.ofNullable(user).map(User::getUserName).orElse("default name");
            System.out.println(userName);
    
            System.out.println();
        }
    
    
        /**
         * 将二维列表转换为一维列表
         */
        public static void flatMap() {
            List<Integer> list1 = Arrays.asList(1, 2, 3);
            List<Integer> list2 = Arrays.asList(4, 5, 6);
            List<Integer> list3 = Arrays.asList(7, 8);
            List<List<Integer>> ll1 = newArrayList();
            ll1.add(list1);
            ll1.add(list2);
            ll1.add(list3);
            List<Integer> result = ll1.stream().flatMap(list -> list.stream())
                    .collect(Collectors.toList());
            System.out.println(result);
    
            System.out.println();
        }
    
    }
    
    • 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
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283
    • 284
    • 285
    • 286
    • 287
    • 288
    • 289
    • 290
    • 291
    • 292
    • 293
    • 294
    • 295
    • 296
    • 297
    • 298
    • 299
    • 300
    • 301
    • 302
    • 303
    • 304
    • 305
    • 306
    • 307
    • 308
    • 309
    • 310
    • 311
    • 312
    • 313
    • 314
    • 315
    • 316
    • 317
    • 318
    • 319
    • 320
    • 321
    • 322
    • 323
    • 324
    • 325
    • 326
    • 327
    • 328
    • 329
    • 330
    • 331
    • 332
    • 333
    • 334
    • 335
    • 336
    • 337
    • 338
    • 339
    • 340
    • 341
    • 342
    • 343
    • 344
    • 345
    • 346
    • 347
    • 348
    • 349
    • 350
    • 351
    • 352
    • 353
    • 354
    • 355
    • 356
    • 357
    • 358
    • 359
    • 360
    • 361
    • 362
    • 363
    • 364
    • 365
    • 366
    • 367
    • 368
    • 369
    • 370
    • 371
    • 372
    • 373
    • 374
    • 375
    • 376
    • 377
    • 378
    • 379
    • 380
    • 381
  • 相关阅读:
    实验20:火焰报警器实验
    产品经理基础(一)
    IO流(字节流与字符流) 和 File对象 详解与使用
    CanvasJS JavaScript 3.7.1 Crack
    学生个人网页设计作品 学生个人网页模板 简单个人主页成品 个人网页制作 HTML学生个人网站作业设计
    CSDN 大规模抓取 GitHub 上的项目到 GitCode,伪造开发者主页引公愤
    3.Java线程的状态
    交换机配置参考案例
    RocketMQ安装部署
    4G dtu远程无线抄表
  • 原文地址:https://blog.csdn.net/godloveleo9527/article/details/126212544