Java8Stream

news2025/2/25 8:59:21

目录

什么是Stream?

IO流:

Java8Stream:

什么是流?

stream图解

获取流

集合类,使用 Collection 接口下的 stream()

代码

数组类,使用 Arrays 中的 stream() 方法

代码

stream,使用 Stream 中的静态方法

代码

流操作

按步骤写

代码

链式调用

代码

运行

中间操作:

 API

代码 

运行

代码 

运行

代码

运行 

终端操作:

API

代码

运行

代码

运行

代码

运行

代码

运行

代码

运行

代码

运行


什么是Stream?

IO流:

输入输出文件的

Java8Stream:

处理数据集合(数组,集合类);

对数组,集合类 进行各种操作(过滤,排序......);

stream处理数据的大体过程:

数组/集合类-->流-->各种操作(排序,过滤...)-->结果。

什么是流?

数据和集合类更偏向于存储数据(各种结构);

stream更偏向于数据操作。

stream图解

获取流

获取流,把集合或者数组转化为stream对象。

集合类,使用 Collection 接口下的 stream()
代码
package com.ffyc.stream;

import java.util.ArrayList; 
import java.util.stream.Stream;

public class Demo1 {
    public static void main(String[] args) { 
        ArrayList<Integer> arrayList = new ArrayList<>();
        arrayList.add(1);
        arrayList.add(2);
        arrayList.add(3);
        arrayList.add(4);
        //把集合转为流
        Stream<Integer> stream = arrayList.stream(); 
    }
}
数组类,使用 Arrays 中的 stream() 方法
代码
package com.ffyc.stream; 

import java.util.Arrays;
import java.util.stream.IntStream; 

public class Demo1 {
    public static void main(String[] args) { 
        int[] array = new int[]{1,2,3,4};
        //把数组转为流
        IntStream intStream = Arrays.stream(array); 
    }
}
stream,使用 Stream 中的静态方法
代码
package com.ffyc.stream;

import java.util.stream.Stream;

public class Demo1 {
    public static void main(String[] args) { 
        Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5);
    }
}

流操作

按步骤写
代码
package com.ffyc.stream;

 
import java.util.Arrays;
import java.util.stream.Stream;

public class Demo2 {
    public static void main(String[] args) {   
        Integer[] array = new Integer[]{1,2,3,4,5};
        Stream<Integer> stream = Arrays.stream(array);
        Stream stream1 = stream.filter();
        Stream stream2 = stream1.sorted();
    }
}
链式调用
代码
package com.ffyc.stream;


import java.util.Arrays;
import java.util.stream.Stream;

public class Demo2 {
    public static void main(String[] args) { 
        long sum = Arrays.stream(array)
                .sorted()
                .count();
    }
}
运行

中间操作:

流的各种数据处理

 API

filter:过滤流中的某些元素,
sorted(): 自然排序,流中元素需实现 Comparable 接口
distinct: 去除重复元素 

代码 
package com.ffyc.stream;


import java.util.Arrays; 

public class Demo2 {
    public static void main(String[] args) { 
        Integer[] array = new Integer[]{1,2,3,4,2,5}; 
        Arrays.stream(array)
                .filter((e)->{
                    return e<5;
                })
                .sorted((o1,o2)->{
                    return o2-o1;
                })
                .distinct()
                .forEach((e)->{
                    System.out.println(e);
                });
    }
}
运行

limit(n): 获取 n 个元素
skip(n): 跳过 n 元素,配合 limit(n)可实现分页

代码 
package com.ffyc.stream;


import java.util.Arrays; 

public class Demo2 {
    public static void main(String[] args) { 
        Integer[] array = new Integer[]{1,2,3,4,2,5}; 
        Arrays.stream(array)
                //跳过指定数量个元素
                .skip(2)
                //取出指定数量个元素
                .limit(2)
                .forEach((e)->{
                    System.out.println(e);
                }); 
    }
}
运行

map():将其映射成一个新的元素

代码
package com.ffyc.stream;
 

public class Student {
    private int num;
    private String name;
    private int age;

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

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "num=" + num +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
package com.ffyc.stream;

import java.util.ArrayList;
import java.util.Arrays; 
import java.util.Map;
import java.util.stream.Collectors;

public class Demo4 {
    public static void main(String[] args) {
        Student s1 = new Student(001,"张三",18);
        Student s2 = new Student(002,"李四",19);
        Student s3 = new Student(003,"王五",29);
        Student s4 = new Student(004,"王麻子",21);
        Student s5 = new Student(005,"丽丽",19);

        ArrayList<Student> students = new ArrayList<>();
        students.add(s3);
        students.add(s1);
        students.add(s2);
        students.add(s5);
        students.add(s4); 

        Object[] array = students.stream()
                .map((Student::getNum))//将对象中某个属性的值映射到一个新集合中
                .toArray();
        System.out.println(Arrays.toString(array));

        Map<Integer, String> map = students.stream()
                .collect(Collectors.toMap(Student::getNum, Student::getName));
        System.out.println(map);
    }
}
运行 

终端操作:

把流转为最终结果(数组/集合/单值)

API

Min:返回流中元素最小值
Max:返回流中元素最大值 

代码
package com.ffyc.stream;

import java.util.Arrays; 

public class Demo3 {
    public static void main(String[] args) { 
        Integer[] array = new Integer[]{1,2,3,4,2,5};
        Integer max = Arrays.stream(array)
                .distinct()
                .max((o1, o2) -> {//最大值
                    return o1 - o2;
                }).get();
        System.out.println(max);

        Integer min = Arrays.stream(array)
                .distinct()
                .min((o1, o2) -> {//最小值
                    return o1 - o2;
                }).get();
        System.out.println(min); 
}
运行

count:返回流中元素的总个数

代码
package com.ffyc.stream;

import java.util.Arrays; 

public class Demo3 {
    public static void main(String[] args) { 
        Integer[] array = new Integer[]{1,2,3,4,2,5}; 

        long count = Arrays.stream(array)
                .distinct()
                .count();//统计元素个数
        System.out.println(count); 
    }
}
运行

Reduce:所有元素求和

代码
package com.ffyc.stream;

import java.util.Arrays; 

public class Demo3 {
    public static void main(String[] args) { 
        Integer[] array = new Integer[]{1,2,3,4,2,5}; /

        long reduce = Arrays.stream(array)
                .distinct()
                .reduce((a,b)->{//求和
                    return a+b;
                }).get();
        System.out.println(reduce); 
    }
}
运行

anyMatch:接收一个 Predicate 函数,只要流中有一个元素满足条件则返回 true,否则返回 false
allMatch:接收一个 Predicate 函数,当流中每个元素都符合条件时才返回 true,否则返回 false

代码
package com.ffyc.stream;

import java.util.Arrays; 

public class Demo3 {
    public static void main(String[] args) { 
        Integer[] array = new Integer[]{1,2,3,4,2,5}; 

        Boolean result1 = Arrays.stream(array)
                .distinct()
                .anyMatch((e)->{//只有有一个元素满足条件,返回true
                    return e>2;
                });
        System.out.println(result1);

        Boolean result2 = Arrays.stream(array)
                .distinct()
                .allMatch((e)->{//所有的条件都满足条件,返回true
                    return e>2;
                });
        System.out.println(result2); 
    }
}
运行

findFirst:返回流中第一个元素

代码
package com.ffyc.stream;

import java.util.Arrays; 

public class Demo3 {
    public static void main(String[] args) { 
        Integer[] array = new Integer[]{1,2,3,4,2,5}; 

        Integer result = Arrays.stream(array)
                .distinct()
                .findFirst()
                .get();
        System.out.println(result);
    }
}
运行

collect:将流中的元素倒入一个集合,Collection 或 Map

代码
package com.ffyc.stream;
 

public class Student {
    private int num;
    private String name;
    private int age;

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

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "num=" + num +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
package com.ffyc.stream;

import java.util.ArrayList; 
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Demo4 {
    public static void main(String[] args) {
        Student s1 = new Student(001,"张三",18);
        Student s2 = new Student(002,"李四",19);
        Student s3 = new Student(003,"王五",29);
        Student s4 = new Student(004,"王麻子",21);
        Student s5 = new Student(005,"丽丽",19);

        ArrayList<Student> students = new ArrayList<>();
        students.add(s3);
        students.add(s1);
        students.add(s2);
        students.add(s5);
        students.add(s4);

        List<Student> collect = students.stream()
                .sorted((a,b)->{ //对学生对象集合进行排序,必须给定排序的规则
                    return a.getNum()-b.getNum();
                })
                .collect(Collectors.toList());
        System.out.println(collect);

        List<Student> res = students.stream()
                .filter((stu) -> {
                  return  stu.getAge()>18;
                })
                .collect(Collectors.toList());
        System.out.println(res);

        List<Integer> list = students.stream()
                .map(Student::getNum)
                .collect(Collectors.toList());
        System.out.println(list);
    }
}
运行

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1704091.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

智慧水坝:科技变革的里程碑

在曾经的水利工程领域&#xff0c;水坝只是为了水资源的调配和控制&#xff0c;提供一定的安全储备。然而&#xff0c;随着现代科技的不断发展&#xff0c;传统的水坝已经不再是单一的水源控制工程&#xff0c;而是变成了一个充满智慧与创新的生态系统。智慧水坝的概念已经超越…

【机器学习】SUTRA引领多语言处理

在人工智能的浪潮中&#xff0c;自然语言处理&#xff08;NLP&#xff09;技术一直是备受瞩目的焦点。随着全球化和信息时代的到来&#xff0c;多语言处理能力成为了评估NLP技术优劣的重要标准。近期&#xff0c;一款名为SUTRA的多语言大型语言模型架构引起了业界的广泛关注。它…

CRLF注入漏洞

1.CRLF注入漏洞原理 Nginx会将 $uri进行解码&#xff0c;导致传入%0a%0d即可引入换行符&#xff0c;造成CRLF注入漏洞。 执行xss语句 2.漏洞扩展 CRLF 指的是回车符(CR&#xff0c;ASCII 13&#xff0c;\r&#xff0c;%0d) 和换行符(LF&#xff0c;ASCII 10&#xff0c;\n&am…

Java项目:基于SSM框架实现的企业人事管理系统单位人事管理系统【ssm+B/S架构+源码+数据库+毕业论文】

一、项目简介 本项目是一套基于SSM框架实现的企业人事管理系统单位人事管理系统 包含&#xff1a;项目源码、数据库脚本等&#xff0c;该项目附带全部源码可作为毕设使用。 项目都经过严格调试&#xff0c;eclipse或者idea 确保可以运行&#xff01; 该系统功能完善、界面美观…

M功能-open feign的使用-支付系统(四)

target&#xff1a;离开柬埔寨倒计时-219day 这张图片一直是我idea的背景图&#xff0c;分享出来啦… 前言 支付平台使用的是基于springcloud的微服务&#xff0c;服务之间的调用都是使用openfeign&#xff0c;而我们每个服务对外暴露的接口响应都会在外部封装一层code之类的信…

零售EDI:Target DVS EDI项目案例

Target塔吉特是美国一家巨型折扣零售百货集团&#xff0c;与全球供应商建立长远深入的合作关系&#xff0c;目前国内越来越多的零售产品供应商计划入驻Target。完成入驻资格审查之后&#xff0c;Target会向供应商提出EDI对接邀请&#xff0c;企业需要根据指示完成供应商EDI信息…

人脸识别——筛选与删除重复或近似重复数据提高人脸识别的精确度

1. 概述 人脸识别研究通常使用从网上收集的人脸图像数据集&#xff0c;但这些数据集可能包含重复的人脸图像。为了解决这个问题&#xff0c;我们需要一种方法来检测人脸图像数据集中的重复图像&#xff0c;并提高其质量。本文介绍了一种检测人脸图像数据集中重复图像的方法。该…

英语新概念2-回译法-lesson16

第一次回译 if you ___ your car on a wrong place, the traffic police man will find you quickly. If he do not give you the ticket,you are lucky.However,the ___ not all like this,The police man is __ sometimes.I had a holiday in Sweden, I found a ___ in my c…

基于PostGIS的mvt动态矢量切片的后台地图服务和前端调用

目录 一、背景 二、矢量切片 三、Mapbox的矢量切片格式 四、PostGIS生成矢量切片 ST_AsMVT: ST_AsMVTGeom: 五、导入试验数据 六、编写PostGIS函数 七:Java后端实现 八、Openlayers前端调用 一、背景 矢量切片技术目前已成为互联网地图的主流技术,无论是Mapbox还…

项目引用图片后乱码?

用的墨刀原型-标注 把上面图标库的图片下载为png图片在项目中引用了&#xff0c;结果直接项目起来&#xff0c;全都是乱码 经过排查是墨刀图标库图片的问题&#xff0c;把图片重新用管理员账户登录导出图片后再试试

java并发工具类都有哪些

Java中的并发工具类包括&#xff1a; CountDownLatch CountDownLatch允许一个或多个线程等待其他线程完成某些操作。它通常用于线程间的同步&#xff0c;例如在一个线程完成其工作后通知其他线程继续执行。 CyclicBarrier CyclicBarrier是一个同步辅助类&#xff0c;它允许一…

Java项目:基于SSM框架实现的学生就业管理系统分前后台(ssm+B/S架构+源码+数据库+毕业论文+开题报告)

一、项目简介 本项目是一套基于SSM框架实现的学生就业管理系统 包含&#xff1a;项目源码、数据库脚本等&#xff0c;该项目附带全部源码可作为毕设使用。 项目都经过严格调试&#xff0c;eclipse或者idea 确保可以运行&#xff01; 该系统功能完善、界面美观、操作简单、功能…

PHP深入理解-PHP架构布局

PHP的架构布局涉及多个层次&#xff0c;让我们一起探讨一下吧&#xff01;&#x1f680; 执行流程&#xff1a;解析为Token&#xff1a;将PHP代码解析成标记&#xff08;tokens&#xff09;。抽象语法树&#xff1a;将语法解析树转换为抽象语法树。Opcodes&#xff1a;将抽象语…

亚马逊测评自养号:轻松掌握运营技巧提升店铺流量

亚马逊平台运营全流程&#xff0c;是每位卖家在电商领域走向成功的必经之路。从产品选择、上架优化&#xff0c;到营销推广、订单处理&#xff0c;每一环节都需精心策划与执行&#xff0c;下面具体介绍亚马逊平台运营全流程是什么&#xff1f; 一、亚马逊平台运营全流程是什么…

云服务器购买之后到部署项目的流程

1.通过账号密码登录百度智能云控制台; 2.进入对应的服务器‘云服务器BBC’ 找到’实例‘即找到对应的服务器列表; 此时通过本地电脑 1.cmd命令提示符 PING 服务器公网地址不通&#xff1b; 2.通过本地电脑进行远程桌面连接不通 原因&#xff1a;没有关联安全组&#xff0c;或者…

如何处理逻辑设计中的时钟域

1.什么是时钟域 2.PLL对时钟域管理 不管是否需要变频变相&#xff0c;在FPGA内部将外部输入时钟从专用时钟引脚扇入后先做PLL处理。如何调用pll&#xff0c;见另一篇文章。 约束输入时钟 creat_clock -period 10 -waveform {0 5} [get_ports {sys_clk}] 3.单bit信号跨时钟…

深入探索python编程中的字典结构

新书上架~&#x1f447;全国包邮奥~ python实用小工具开发教程http://pythontoolsteach.com/3 欢迎关注我&#x1f446;&#xff0c;收藏下次不迷路┗|&#xff40;O′|┛ 嗷~~ 目录 一、字典的特点与基础操作 二、安全访问与哈希函数 三、字典的应用案例 四、总结 在编程的…

MySQL:CRUD初阶(有图有实操)

文章目录 &#x1f4d1;1. 数据库的操作&#x1f324;️1.1 显示当前的数据库&#x1f324;️1.2 创建数据库&#x1f324;️1.3 选中数据库&#x1f324;️1.4 删除数据库 &#x1f4d1;2. 表的操作&#x1f324;️2.1 查看表结构&#x1f324;️2.2 创建表&#x1f324;️2.3…

选项卡式小部件QTabWidget

文章目录 1. 详细介绍2. 常用属性3. 信号4. 常用函数5. 官方示例Tab Dialog QTabWidget提供一堆选项卡式小部件。 1. 详细介绍 选项卡式部件提供一个选项卡栏和一个用于显示与每个选项卡相关的页面的页面区域。 默认情况下&#xff0c;选项卡栏显示在页面区域上方&#xff0c;…

探索编程逻辑中的“卡特牛(continue)”魔法

新书上架~&#x1f447;全国包邮奥~ python实用小工具开发教程http://pythontoolsteach.com/3 欢迎关注我&#x1f446;&#xff0c;收藏下次不迷路┗|&#xff40;O′|┛ 嗷~~ 目录 一、引言&#xff1a;卡特牛逻辑的魅力 二、卡特牛逻辑的解析 三、卡特牛逻辑的应用实例 …