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

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

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));
    }
}
相关推荐
sino爱学习9 分钟前
高性能线程池实践:Dubbo EagerThreadPool 设计与应用
java·后端
m0_7155753410 分钟前
使用PyTorch构建你的第一个神经网络
jvm·数据库·python
甄心爱学习12 分钟前
【leetcode】判断平衡二叉树
python·算法·leetcode
深蓝电商API15 分钟前
滑块验证码破解思路与常见绕过方法
爬虫·python
阿猿收手吧!16 分钟前
【C++】string_view:高效字符串处理指南
开发语言·c++
Ulyanov17 分钟前
Pymunk物理引擎深度解析:从入门到实战的2D物理模拟全攻略
python·游戏开发·pygame·物理引擎·pymunk
sensen_kiss29 分钟前
INT303 Coursework1 爬取影视网站数据(如何爬虫网站数据)
爬虫·python·学习
风生u42 分钟前
activiti7 详解
java
玄同7651 小时前
我的 Trae Skill 实践|使用 UV 工具一键搭建 Python 项目开发环境
开发语言·人工智能·python·langchain·uv·trae·vibe coding
岁岁种桃花儿1 小时前
SpringCloud从入门到上天:Nacos做微服务注册中心(二)
java·spring cloud·微服务