Java lambda表达式使用笔记

2023-05-16

package com.allsaints.music.admin;

import com.allsaints.music.admin.service.entrymgr.bak.Student;
import lombok.Data;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.averagingInt;
import static java.util.stream.Collectors.maxBy;

public class LambdaTest {

    @Data
    public static class Student {
        private String name;
        private int age;
        private int stature;

        public Student(String name, int age, int stature) {
            this.name = name;
            this.age = age;
            this.stature = stature;
        }
    }

    @Data
    public static class OutstandingClass {
        private String name;
        List<Student> stu;

        public OutstandingClass(String name, List<Student> stu) {
            this.name = name;
            this.stu = stu;
        }

        public OutstandingClass() {

        }

        public List<Student> getStudents() {
            return stu;
        }
    }

    /**
     * 演示自定义函数式接口使用
     *
     * @param worker
     */
    public static void test(Worker worker) {
        String work = worker.work();
        System.out.println(work);
    }

    public interface Worker {
        String work();
    }

//    public static void main(String[] args) {
//
//        Student student = new Student("9龙", 23, 175);
//
//        // 断言 判断 false
//        Predicate<Integer> predicate = x -> x > 185;
//        System.out.println("9龙的身高高于185吗?:" + predicate.test(student.getStature()));
//
//        Consumer<String> consumer = System.out::println;
//        consumer.accept("命运由我不由天");
//
//        Function<Student, String> function = Student::getName;
//        String name = function.apply(student);
//        System.out.println(name);
//
//        Supplier<Integer> supplier =
//                () -> Integer.valueOf(BigDecimal.TEN.toString());
//        System.out.println(supplier.get());
//
//        UnaryOperator<Boolean> unaryOperator = uglily -> !uglily;
//        Boolean apply2 = unaryOperator.apply(true);
//        System.out.println(apply2);
//
//        BinaryOperator<Integer> operator = (x, y) -> x * y;
//        Integer integer = operator.apply(2, 3);
//        System.out.println(integer);
//
//        test(() -> "我是一个演示的函数式接口");
//        //9龙的身高高于185吗?:false
//        //命运由我不由天
//        //9龙
//        //10
//        //false
//        //6
//        //我是一个演示的函数式接口
//    }


    //    2、常用的流
//        2.1 collect(Collectors.toList()) 将流转换为list。还有toSet(),toMap()等。及早求值。
//    public static void main(String[] args) {
//        List<Student> studentList = Stream.of(
//                new Student("路飞", 22, 175),
//                new Student("红发", 40, 180),
//                new Student("白胡子", 50, 185)
//        ).collect(Collectors.toList());
//        System.out.println(studentList);
//    }

//输出结果
//[Student{name='路飞', age=22, stature=175, specialities=null},
//Student{name='红发', age=40, stature=180, specialities=null},
//Student{name='白胡子', age=50, stature=185, specialities=null}]

//2.2 filter 顾名思义,起过滤筛选的作用。内部就是Predicate接口。惰性求值。
//        比如我们筛选出出身高小于180的同学。

//    public static void main(String[] args) {
//        List<Student> students = new ArrayList<>(3);
//        students.add(new Student("路飞", 22, 175));
//        students.add(new Student("红发", 40, 180));
//        students.add(new Student("白胡子", 50, 185));
//
//        List<Student> list = students.stream()
//                .filter(stu -> stu.getStature() < 180)
//                .collect(Collectors.toList());
//        System.out.println(list);
//    }
//输出结果
//[Student{name='路飞', age=22, stature=175, specialities=null}]

//2.3 map 转换功能,内部就是Function接口。惰性求值

//    public static void main(String[] args) {
//        List<Student> students = new ArrayList<>(3);
//        students.add(new Student("路飞", 22, 175));
//        students.add(new Student("红发", 40, 180));
//        students.add(new Student("白胡子", 50, 185));
//
//        List<String> names = students.stream().map(Student::getName).collect(Collectors.toList());
//        System.out.println(names);
//    }
输出结果
[路飞, 红发, 白胡子]
//例子中将student对象转换为String对象,获取student的名字。


//        2.4 flatMap 将多个Stream合并为一个Stream。惰性求值

//    public static void main(String[] args) {
//        List<Student> students = new ArrayList<>(3);
//        students.add(new Student("路飞", 22, 175));
//        students.add(new Student("红发", 40, 180));
//        students.add(new Student("白胡子", 50, 185));
//
//        List<Student> students2 = new ArrayList<>(3);
//        students2.add(new Student("艾斯", 25, 183));
//        students2.add(new Student("雷利", 48, 176));
//
//        List<Student> studentList = Stream.of(students,students2,
//                Arrays.asList(new Student("艾斯1", 25, 183),
//                        new Student("雷利2", 48, 176)))
//                .flatMap(Collection::stream).collect(Collectors.toList());
//        System.out.println(studentList);
//    }
//输出结果
//[Student{name='路飞', age=22, stature=175, specialities=null},
//Student{name='红发', age=40, stature=180, specialities=null},
//Student{name='白胡子', age=50, stature=185, specialities=null},
//Student{name='艾斯', age=25, stature=183, specialities=null},
//Student{name='雷利', age=48, stature=176, specialities=null}]
// 调用Stream.of的静态方法将两个list转换为Stream,再通过flatMap将两个流合并为一个。


    //    2.5 max和min 我们经常会在集合中求最大或最小值,使用流就很方便。及早求值。
//    public static void main(String[] args) {
//        List<Student> students = new ArrayList<>(3);
//        students.add(new Student("路飞", 22, 175));
//        students.add(new Student("红发", 40, 180));
//        students.add(new Student("白胡子", 50, 185));
//
//        Optional<Student> max = students.stream().max(Comparator.comparing(Student::getAge));
//        Optional<Student> min = students.stream().min(Comparator.comparing(stu -> stu.getAge()));
//        //判断是否有值
//        max.ifPresent(System.out::println);
//
//        if (min.isPresent()) {
//            System.out.println(min.get());
//        }
//    }
//输出结果
//Student{name='白胡子', age=50, stature=185, specialities=null}
//Student{name='路飞', age=22, stature=175, specialities=null}
//max、min接收一个Comparator(例子中使用java8自带的静态函数,只需要传进需要比较值即可。)并且返回一个Optional对象,该对象是java8新增的类,专门为了防止null引发的空指针异常。
// 可以使用max.isPresent()判断是否有值;可以使用max.orElse(new Student()),当值为null时就使用给定值;也可以使用max.orElseGet(() -> new Student());这需要传入一个Supplier的lambda表达式。

//    2.6 count 统计功能,一般都是结合filter使用,因为先筛选出我们需要的再统计即可。及早求值
//    public static void main(String[] args) {
//        List<Student> students = new ArrayList<>(3);
//        students.add(new Student("路飞", 22, 175));
//        students.add(new Student("红发", 40, 180));
//        students.add(new Student("白胡子", 50, 185));
//
//        long count = students.stream().filter(s1 -> s1.getAge() < 45).count();
//        System.out.println("年龄小于45岁的人数是:" + count);
//    }
//输出结果
//年龄小于45岁的人数是:2


    //2.7 reduce reduce 操作可以实现从一组值中生成一个值。在上述例子中用到的 count 、 min 和 max 方 法,因为常用而被纳入标准库中。事实上,这些方法都是 reduce 操作。及早求值。

//    public static void main(String[] args) {
//        Integer reduce = Stream.of(1, 2, 3, 4).reduce(0, (acc, x) -> acc+ x);
//        System.out.println(reduce);
//    }
//输出结果
//10
//我们看得reduce接收了一个初始值为0的累加器,依次取出值与累加器相加,最后累加器的值就是最终的结果。

//        三、高级集合类及收集器
//        3.1 转换成值
//        收集器,一种通用的、从流生成复杂值的结构。只要将它传给 collect 方法,所有 的流就都可以使用它了。\
//        标准类库已经提供了一些有用的收集器,以下示例代码中的收集器都是从 java.util.stream.Collectors 类中静态导入的。


//    public static void main(String[] args) {
//        List<Student> students1 = new ArrayList<>(3);
//        students1.add(new Student("路飞", 23, 175));
//        students1.add(new Student("红发", 40, 180));
//        students1.add(new Student("白胡子", 50, 185));
//
//        OutstandingClass ostClass1 = new OutstandingClass("一班", students1);
//        //复制students1,并移除一个学生
//        List<Student> students2 = new ArrayList<>(students1);
//        students2.remove(1);
//        OutstandingClass ostClass2 = new OutstandingClass("二班", students2);
//        //将ostClass1、ostClass2转换为Stream
//        Stream<OutstandingClass> classStream = Stream.of(ostClass1, ostClass2);
//        OutstandingClass outstandingClass = biggestGroup(classStream);
//        System.out.println("人数最多的班级是:" + outstandingClass.getName());
//
//        System.out.println("一班平均年龄是:" + averageNumberOfStudent(students1));
//    }

    /**
     * 获取人数最多的班级
     */
    private static OutstandingClass biggestGroup(Stream<OutstandingClass> outstandingClasses) {
        return outstandingClasses.max(comparing(ostClass -> ostClass.getStudents().size()))
                .orElseGet(OutstandingClass::new);
    }

    /**
     * 计算平均年龄
     */
    private static double averageNumberOfStudent(List<Student> students) {
        return students.stream().collect(averagingInt(Student::getAge));
    }

//输出结果
//人数最多的班级是:一班
//一班平均年龄是:37.666666666666664
//maxBy或者minBy就是求最大值与最小值。


//    3.2 转换成块 常用的流操作是将其分解成两个集合,Collectors.partitioningBy帮我们实现了,接收一个Predicate函数式接口。
//        将示例学生分为会唱歌与不会唱歌的两个集合。

//    public static void main(String[] args) {
//        //省略List<student> students的初始化
//        Map<Boolean, List<Student>> listMap = students.stream().collect(
//                Collectors.partitioningBy(student -> student.getSpecialities().
//                        contains(SpecialityEnum.SING)));
//    }


//3.3 数据分组 数据分组是一种更自然的分割数据操作,与将数据分成 ture 和 false 两部分不同,可以使用任意值对数据分组。Collectors.groupingBy接收一个Function做转换。
//        如图,我们使用groupingBy将根据进行分组为圆形一组,三角形一组,正方形一组。
//        例子:根据学生第一个特长进行分组

//    public static void main(String[] args) {
//        //省略List<student> students的初始化
//        Map<SpecialityEnum, List<Student>> listMap = students.stream().collect(Collectors.groupingBy(student -> student.getSpecialities().get(0)));
//    }
//    Collectors.groupingBy与SQL 中的 group by 操作是一样的。


//        3.4 字符串拼接
//        如果将所有学生的名字拼接起来,怎么做呢?通常只能创建一个StringBuilder,循环拼接。使用Stream,使用Collectors.joining()简单容易。

    public static void main(String[] args) {
        List<Student> students = new ArrayList<>(3);
        students.add(new Student("路飞", 22, 175));
        students.add(new Student("红发", 40, 180));
        students.add(new Student("白胡子", 50, 185));

        String names = students.stream().map(Student::getName).collect(Collectors.joining(",", "[", "]"));
        System.out.println(names);
    }
//输出结果
//[路飞,红发,白胡子]
//joining接收三个参数,第一个是分界符,第二个是前缀符,第三个是结束符。也可以不传入参数Collectors.joining(),这样就是直接拼接。

}





本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java lambda表达式使用笔记 的相关文章

随机推荐

  • netbeans中配置maven

    deploy 发布到远程maven库 本节默认maven库为nexus netbeans中按ctrl 43 1 xff0c 打开Project窗口 xff1b 在Project窗口中找到相关的project或module 在项目名上点击鼠标
  • 订阅关系一致

    订阅关系一致指的是同一个消费者Group ID下所有Consumer实例所订阅的Topic Tag必须完全一致 如果订阅关系不一致 消息消费的逻辑就会混乱 甚至导致消息丢失 本文提供订阅关系一致的正确示例代码以及订阅关系不一致的可能原因 帮
  • java之PO,VO,TO,QO,BO等

    PO persistant object 持久对象 在 o r 映射的时候出现的概念 xff0c 如果没有 o r 映射 xff0c 没有这个概念存在了 通常对应数据模型 数据库 xff0c 本身还有部分业务逻辑的处理 可以看成是与数据库中
  • 多生产者多消费者问题的无锁队列实现

    背景 代码根据论文 Implementing Lock Free Queues 复现 背景知识博客 xff1a 左耳朵耗子博客 https coolshell cn articles 8239 html 代码地址 xff1a https g
  • Ubuntu18下Github+Hexo搭建博客教程

    我的博客 xff0c 欢迎来访 xff1a www zxwsbg cn 搭建 安装git nodejs sudo apt get install git sudo apt get install nodejs sudo apt get in
  • linux中提供了PF_PACKET接口可以操作链路层的数据

    http blog sina com cn s blog 82f2fc28010132og html sock raw xff08 注意一定要在root下使用 xff09 原始套接字编程可以接收到本机网卡上的数据帧或者数据包 对于监听网络的
  • 分享52个Java源码,总有一款适合您

    Java源码 分享52个Java源码 xff0c 总有一款适合您 下面是文件的名字 xff0c 我放了一些图片 xff0c 文章里不是所有的图主要是放不下 xff0c 大家下载后可以看到 源码下载链接 xff1a https pan bai
  • 抽象类中的方法该如何实现呢?

    本节通过一个案例来学习如何实现抽象类中的方法 xff0c 具体步骤如下 xff1a 1 创建Animal类 创建一个Animal抽象类 xff0c 并在类中定义一个抽象call 方法 xff0c 如文件3 25所示 文件3 25Animal
  • zset类型的底层数据结构的实现

    参考资料 xff1a redis中zset底层实现原理 渣渣 CSDN博客 zset底层数据结构 redis的zset数据结构 xff1a 跳表 知乎 zset类型的底层数据结构的实现 xff1f zset是Redis提供的一个非常特别的数
  • XD软件都有哪些基础操作?

    下面我们来学习一下XD软件的基础操作 xff0c 包括资产面板的功能 交互动作 一键切图等等 1 重复网格 xff08 1 xff09 重复网格可智能复制其选择对象 xff0c 并批量更换图片 修改文字 之间距离等 xff08 2 xff0
  • 3分钟掌握7个XD基础操作

    下面我们来学习一下XD软件的基础操作 xff0c 包括资产面板的功能 交互动作 一键切图等等 1 重复网格 xff08 1 xff09 重复网格可智能复制其选择对象 xff0c 并批量更换图片 修改文字 之间距离等 xff08 2 xff0
  • 目标跟踪常用算法——EKF篇

    目录 1 扩展卡尔曼滤波算法 1 1 扩展卡尔曼滤波算法简单介绍 1 2 扩展卡尔曼滤波算法流程 1 3 扩展卡尔曼滤波算法仿真分析 2 参考文献 1 扩展卡尔曼滤波算法 1 1 扩展卡尔曼滤波算法简单介绍 对于非线性滤波问题 xff0c
  • 人工智能概述

    目录 什么是人工智能实现人工智能的方法逻辑编程机器学习深度学习机器学习和深度学习的区别 人工智能的分类如何实现人工智能 什么是人工智能 人工智能 又被称为机器智能 xff0c 是一种综合计算机科学 统计学 语言学等多种学科 xff0c 使机
  • java注解(annotation)的执行顺序

    可以在切面上使用 64 Order注解 如 64 Component 64 Aspect 64 Order 1 public class Aspect1 64 Component 64 Aspect 64 Order 2 public cl
  • Eclipse 常用快捷键 (动画讲解)

    Eclipse 常用快捷键 动画讲解 Eclipse有强大的编辑功能 xff0c 工欲善其事 xff0c 必先利其器 xff0c 掌握Eclipse快捷键 xff0c 可以大大提高工作效率 小坦克我花了一整天时间 xff0c 精选了一些常用
  • javaweb三大框架SSH

    1 MVC三层架构 xff1a 模型层 xff0c 控制层和视图层 模型层 xff0c 用Hibernate框架让来JavaBean在数据库生成表及关联 xff0c 通过对JavaBean的操作来 对数据库进行操作 xff1b 控制层 xf
  • HTTP请求方式及区别

    GET 向特定的路径资源发出请求 xff0c 数据暴露在url中 POST 向指定路径资源提交数据进行处理请求 xff08 一般用于上传表单或者文件 xff09 xff0c 数据包含在请求体中 OPTIONS 返回服务器针对特定资源所支持的
  • C++实现邮件群发的方法

    这篇文章主要介绍了C 43 43 实现邮件群发的方法 较为详细的分析了邮件发送的原理与C 43 43 相关实现技巧 非常具有实用价值 需要的朋友可以参考下 本文实例讲述了C 43 43 实现邮件群发的方法 分享给大家供大家参考 具体如下 x
  • Asp.Net Core IIS发布后PUT、DELETE请求错误405.0 - Method Not Allowed 因为使用了无效方法(HTTP 谓词)

    Asp Net Core IIS发布后PUT DELETE请求错误405 0 Method Not Allowed 因为使用了无效方法 HTTP 谓词 一 在使用Asp net WebAPI 或Asp Net Core WebAPI 时 x
  • Java lambda表达式使用笔记

    package com allsaints music admin import com allsaints music admin service entrymgr bak Student import lombok Data impor