Java重修第九天—Lambda 表达式和Stream

news/2024/6/18 21:31:45 标签: java, python, 开发语言

通过学习本篇文章可以掌握如下知识

Lambda 表达式

Stream


Lambda

Lambda表达式是JDK 8开始新增的一种语法形式;作用: 用于简化 函数式接口 匿名内部类的代码写法

在这里插入图片描述

函数式接口:首先是接口,其次是只有一个抽象方法。

代码实现

java">public class Test {
    public static void main(String[] args) {


        // 匿名内部类写法
        A a = new A() {
            @Override
            public void run() {
                System.out.println("老虎跑的快");
            }
        };

       // lambda写法
        A a1 = ()->{
            System.out.println("龙会在天上飞");
        };

        // 如果只一条命令
        A a2 = ()-> System.out.println("跑不快啊!");
    }
}


interface A{
    void run();
}

在这里插入图片描述

java中Comparator就是一个函数式接口,可以使用lambda进行简化,IDEA中有提示。

在这里插入图片描述

Stream

Stream流是jdk8开始新增的一套API,可以用于操作集合或者数组数据

其优势在于大量结合了Lambda语法风格来编程,使得代码简洁。

可以将stream流想象成一个流水线。

集合或者数组数据输入到流中,中间一些车间能对数据操作,最后再将数据划分或者收集。

因此stream流要以"结束"功能的函数结尾。

过程大致如下:

入门案例

把集合中所有以"张"开头,且是三个字元素存储到一个新的集合。

输入流是集合中的数据

操作的是以"张"开头的三个字的元素

最后结尾是划分到一个新的函数中。

在这里插入图片描述

代码实现

java">public class Test {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("张无忌");
        list.add("周芷若");
        list.add("赵敏");
        list.add("贺强");
        list.add("张三丰");

        List<String> res =
                list.stream(). // 集合数据变成流
                filter(s -> s.startsWith("张") && s.length() == 3).  // 处理数据
                collect(Collectors.toList()); // 收集数据

        System.out.println(res); // [张无忌, 张三丰]
    }
}

总结:学习stream流,就是学习函数用法以及哪些函数是作为最后结尾的哪些是作为中间处理的。

在这里插入图片描述

我将从三个方面详细介绍Stream流

1、获取Steam流

Stream流本质是一个接口,不能直接创建

java">public interface Stream<T> extends BaseStream<T, Stream<T>> {}

那么集合是如何创建呢?集合有一个stream方法,我们可以进入源码看到。

java">default Stream<E> stream() {
    return StreamSupport.stream(spliterator(), false);
}

数据如何获取Stream流呢?,最常用的是第一种。

2、Stream流常见的中间方法

常见方法如下,通过调用中间方法后可以返回一个新的Stream流,继续支持链式编程。

代码操作

需求1:找出成绩大于等于60分的数据,先升序后再输出。

java">public class Test {
    public static void main(String[] args) {
        ArrayList<Double> scores = new ArrayList<>();
        Collections.addAll(scores,88.5,100.0,60.0,99.0,9.5,99.6,25.0);
        // 需求1:找出成绩大于等于60分的数据,先升序后再输出。
//        scores.stream().filter(s-> s >= 60.0).sorted().forEach(System.out::println);
    }
}

需求2:找出年龄大于等于23,且小于等于30的学生,按照年龄降序输出

java">public class Test {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        Student s1 = new Student("蜘蛛精",26,172.5);
        Student s2 = new Student("蜘蛛精",26,172.5);
        Student s3 = new Student("紫霞",23,167.6);
        Student s4 = new Student("白晶晶",25,169.0);
        Student s5 = new Student("牛魔王",35,183.3);
        Student s6 = new Student("牛夫人",34,168.5);
        Collections.addAll(students,s1,s2,s3,s4,s5,s6);
        // 需求2:找出年龄大于等于23,且小于等于30的学生,按照年龄降序输出
        students.stream().filter(s->s.age>=23 && s.age<=30).sorted(((o1, o2) -> o2.age- o1.age)).forEach(System.out::println);
    }
}

需求3:取出身高最高的前3名学生,输出

java">public class Test {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        Student s1 = new Student("蜘蛛精",26,172.5);
        Student s2 = new Student("蜘蛛精",26,172.5);
        Student s3 = new Student("紫霞",23,167.6);
        Student s4 = new Student("白晶晶",25,169.0);
        Student s5 = new Student("牛魔王",35,183.3);
        Student s6 = new Student("牛夫人",34,168.5);
        Collections.addAll(students,s1,s2,s3,s4,s5,s6);
        // 需求3:取出身高最高的前3名学生,输出
        students.stream().sorted((o1, o2) -> (int) (o2.height - o1.height)).limit(3).forEach(System.out::println);
    }
}

需求4:取出身高倒数2的两名学生,并输出

java">public class Test {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        Student s1 = new Student("蜘蛛精",26,172.5);
        Student s2 = new Student("蜘蛛精",26,172.5);
        Student s3 = new Student("紫霞",23,167.6);
        Student s4 = new Student("白晶晶",25,169.0);
        Student s5 = new Student("牛魔王",35,183.3);
        Student s6 = new Student("牛夫人",34,168.5);
        Collections.addAll(students,s1,s2,s3,s4,s5,s6);
        
        students.stream().sorted((o1, o2) -> (int) (o1.height- o2.height)).limit(2).forEach(System.out::println);
    }
}

需求5:找到身高最高的学生对象并输出

java">public class Test {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        Student s1 = new Student("蜘蛛精", 26, 172.5);
        Student s2 = new Student("蜘蛛精", 26, 172.5);
        Student s3 = new Student("紫霞", 23, 167.6);
        Student s4 = new Student("白晶晶", 25, 169.0);
        Student s5 = new Student("牛魔王", 35, 183.3);
        Student s6 = new Student("牛夫人", 34, 168.5);
        Collections.addAll(students, s1, s2, s3, s4, s5, s6);

        // 需求5:找出身高最高的学生并输出
        Student student = students.stream().max((o1, o2) -> Double.compare(o1.height, o2.height)).get();
        System.out.println(student);
    }
}

需求6;找出身高超过168的学生叫什么名字,要求去除重复名字,再输出

java">public class Test {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        Student s1 = new Student("蜘蛛精", 26, 172.5);
        Student s2 = new Student("蜘蛛精", 26, 172.5);
        Student s3 = new Student("紫霞", 23, 167.6);
        Student s4 = new Student("白晶晶", 25, 169.0);
        Student s5 = new Student("牛魔王", 35, 183.3);
        Student s6 = new Student("牛夫人", 34, 168.5);
        Collections.addAll(students, s1, s2, s3, s4, s5, s6);

        // 需求6;找出身高超过168的学生叫什么名字,要求去除重复名字,再输出
        students.stream().filter(s->s.height > 168).map(s->s.name).distinct().forEach(System.out::println);


        // 需要重写equals 和 hashCode
        students.stream().filter(s->s.height > 168).distinct().forEach(System.out::println);
    }
}

3、Stream常见的终结方法

在这里插入图片描述

需求1:找出身高超过170的学生对象,并且放到一个新的集合去

java">public class Test {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        Student s1 = new Student("蜘蛛精", 26, 172.5);
        Student s2 = new Student("蜘蛛精", 26, 172.5);
        Student s3 = new Student("紫霞", 23, 167.6);
        Student s4 = new Student("白晶晶", 25, 169.0);
        Student s5 = new Student("牛魔王", 35, 183.3);
        Student s6 = new Student("牛夫人", 34, 168.5);
        Collections.addAll(students, s1, s2, s3, s4, s5, s6);

        List<Student> collect = students.stream().filter(student -> student.height > 170.0).collect(Collectors.toList());
        System.out.println(collect);

        Student[] students1 = students.stream().filter(student -> student.height > 170.0).toArray(len -> new Student[len]);
        System.out.println(Arrays.toString(students1));
    }
}

http://www.niftyadmin.cn/n/5331901.html

相关文章

010:vue结合el-table实现表格小计总计需求(summary-method)

文章目录 1. 实现效果2. 核心部分3. 完整组件代码4. 注意点 1. 实现效果 2. 核心部分 el-table 添加如下配置&#xff0c;添加 show-summary 属性&#xff0c;配置 summary-method 函数 <el-table.......show-summary:summary-method"getSummaries" >...... …

Linux利用标准c库对文件操作

这里的思路和之前的‘Linux下文件的创建写入读取编程‘的思路是一样的&#xff0c;都是从介绍API的函数功能开始。都是在Linux下操作文件&#xff0c;但是前者是UNIX系统调用函数&#xff0c;后者是ANSIC标准中的C语言库函数。它们有着不同的适用范围&#xff0c;具体有不同&am…

云服务器CVM_弹性云主机_云计算服务器——腾讯云

腾讯云服务器CVM提供安全可靠的弹性计算服务&#xff0c;腾讯云明星级云服务器&#xff0c;弹性计算实时扩展或缩减计算资源&#xff0c;支持包年包月、按量计费和竞价实例计费模式&#xff0c;CVM提供多种CPU、内存、硬盘和带宽可以灵活调整的实例规格&#xff0c;提供9个9的数…

lua使用resty.http做nginx反向代理(https请求,docker容器化部署集群),一个域名多项目转发

下载使用 链接&#xff1a;https://pan.baidu.com/s/1uQ7yCzQsPWsF6xavFTpbZg 提取码&#xff1a;htay –来自百度网盘超级会员V5的分享 在根目录下执行: # 从 github 上下载文件 git clone https://github.com/ledgetech/lua-resty-http.git # 将 lua-resty-http/lib/ 下的 r…

面经-redis

什么是Redis Redis(Remote Dictionary Server)键只能为字符串&#xff0c;值&#xff1a;字符串、列表、集合、散列表、有序集合。Redis 用来做分布式锁。支持事务 、持久化、LUA脚本、LRU驱动事件、多种集群方案。 Redis为什么这么快 完全基于内存&#xff0c;数据结构简单…

Unreal Engine(UE5)中构建离线地图服务

1. 首先需要用到3个软件&#xff0c;Unreal Engine&#xff0c;gis office 和 bigemap离线服务器 Unreal Engine下载地址:点击前往下载页面 Gis office下载地址:点击前往下载页面 Bigemap离线服务器 下载地址: 点击前往下载页面 Unreal Engine用于数字孪生项目开发&#x…

el-dialog嵌套使用,只显示遮罩层的问题

直接上解决方法 <!-- 错误写法 --><el-dialog><el-dialog></el-dialog></el-dialog><!-- 正确写法 --><el-dialog></el-dialog><el-dialog></el-dialog>我是不建议嵌套使用的&#xff0c;平级也能调用&#xff0c…

TypeError the JSON object must be str, bytes or bytearray, not ‘list‘

在使用python的jason库时&#xff0c;偶然碰到以下问题 TypeError: the JSON object must be str, bytes or bytearray, not ‘list’ 通过如下代码可复现问题 >>> a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> import json >>> ra json.loads(a) Trac…