Java Stream 的常用API
Java Stream 的常用API
遍历(forEach)
package com.liudashuai;import java.util.ArrayList;
import java.util.List;public class Test {public static void main(String[] args) {List<Person> userList = new ArrayList<>();userList.add(new Person("段誉",25));userList.add(new Person("萧峰",40));userList.add(new Person("虚竹",30));userList.add(new Person("无涯子",100));userList.add(new Person("慕容复",35));userList.add(new Person("云中鹤",45));System.out.println(userList);System.out.println("---------------");userList.stream().forEach(u -> {u.setName("天龙八部-" + u.getName());});System.out.println(userList);}
}
class Person{private String name;private int age;public Person(String name, int age) {this.name = name;this.age = age;}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;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", age=" + age +'}';}
}

筛选(filter)
package com.liudashuai;import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;public class Test {public static void main(String[] args) {List<Person> userList = new ArrayList<>();userList.add(new Person("段誉",25));userList.add(new Person("萧峰",40));userList.add(new Person("虚竹",30));userList.add(new Person("无涯子",100));userList.add(new Person("慕容复",35));userList.add(new Person("云中鹤",45));List<Person> collect =userList.stream().filter(user -> (user.getAge() > 30 && user.getName().length() >2)).collect(Collectors.toList());System.out.println(collect);}
}
class Person{private String name;private int age;public Person(String name, int age) {this.name = name;this.age = age;}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;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", age=" + age +'}';}
}

查找(findAny/findFirst)
package com.liudashuai;import java.util.ArrayList;
import java.util.List;public class Test {public static void main(String[] args) {List<Person> userList = new ArrayList<>();userList.add(new Person("段誉",25));userList.add(new Person("萧峰",41));userList.add(new Person("萧峰",42));userList.add(new Person("萧峰",43));userList.add(new Person("虚竹",30));userList.add(new Person("无涯子",100));userList.add(new Person("慕容复",35));userList.add(new Person("云中鹤",45));Person user = userList.stream().filter(u -> u.getName().equals("阿紫")).findAny().orElse(new Person("无",0));System.out.println(user);Person user1 = userList.stream().filter(u -> u.getName().equals("阿紫")).findAny().orElse(null);System.out.println(user1);Person user2 = userList.stream().filter(u -> u.getName().equals("萧峰")).findAny().orElse(null);System.out.println(user2);Person user3 = userList.stream().filter(u -> u.getName().equals("萧峰")).findFirst().orElse(null);System.out.println(user3);}
}
class Person{private String name;private int age;public Person(String name, int age) {this.name = name;this.age = age;}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;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", age=" + age +'}';}
}

- findFirst() 方法根据命名,我们可以大致知道是获取Optional流中的第一个元素。
- findAny() 方法是获取Optional 流中任意一个,存在随机性,其实这里也是获取元素中的第一个,因为是并行流。
注意:在串行流中,findFirst和findAny返回同样的结果;但在并行流中,由于多个线程同时处理,findFirst可能会返回处理结果中的第一个元素,而findAny会返回最先处理完的元素。所以并行流里面使用findAny会更高效。这里并行下findFirst可能返回的不是第一个符合条件的元素吗?我不知道,但是,不重要,因为用得场景不多,因为多线程下,谁是处理结果中的第一个元素一般不重要,因为谁都可能是第一个,所以这里我不去了解findFirst是否可能返回的不是第一个符合条件的元素了。
总之就是串行流下,findFirst和findAny结果一样,并行流下,findAny效率更高,且并行流一般不在意谁是第一个,所以我建议平时使用findAny。
.orElse(null)表示如果一个都没找到返回null。
orElse()中可以塞默认值。如果找不到就会返回orElse中你自己设置的默认值。比如:上面的.orElse(new Person(“无”,0))
转换/去重(map/distinct)
package com.liudashuai;import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;public class Test {public static void main(String[] args) {List<Person> userList = new ArrayList<>();userList.add(new Person("段誉",25));userList.add(new Person("萧峰",41));userList.add(new Person("萧峰",42));userList.add(new Person("虚竹",30));userList.add(new Person("无涯子",100));userList.add(new Person("慕容复",35));userList.add(new Person("云中鹤",45));List<String> nameList = userList.stream().map(Person::getName).collect(Collectors.toList());System.out.println(nameList);List<String> nameList2 = userList.stream().map(Person::getName).distinct().collect(Collectors.toList());System.out.println(nameList2);}
}
class Person{private String name;private int age;public Person(String name, int age) {this.name = name;this.age = age;}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;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", age=" + age +'}';}
}

map的作用:是将输入一种类型,转化为另一种类型,通俗来说:就是将输入类型变成另一个类型。
跳过(limit/skip)
package com.liudashuai;import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;public class Test {public static void main(String[] args) {List<Person> userList = new ArrayList<>();userList.add(new Person("段誉",25));userList.add(new Person("萧峰",41));userList.add(new Person("虚竹",30));userList.add(new Person("无涯子",100));userList.add(new Person("慕容复1",35));userList.add(new Person("慕容复2",35));userList.add(new Person("慕容复3",35));//跳过第一个List<Person> collect = userList.stream().skip(1).collect(Collectors.toList());System.out.println(collect);//只输出前两个元素List<Person> collect2 = userList.stream().limit(2).collect(Collectors.toList());System.out.println(collect2);//跳过前3个元素,然后输出3个元素。可以代替sql中的limit。List<Person> collect3 = userList.stream().skip(3).limit(3).collect(Collectors.toList());System.out.println(collect3);}
}
class Person{private String name;private int age;public Person(String name, int age) {this.name = name;this.age = age;}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;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", age=" + age +'}';}
}

最大值/最小值/平均值(reduce)
package com.liudashuai;import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;public class Test {public static void main(String[] args) {List<Person> userList = new ArrayList<>();userList.add(new Person("段誉",25));userList.add(new Person("萧峰",41));userList.add(new Person("虚竹",30));userList.add(new Person("无涯子",100));userList.add(new Person("慕容复",35));System.out.println("求和");Integer sum1 = userList.stream().map(Person::getAge).reduce(0, Integer::sum);System.out.println(sum1);int sum2 = userList.stream().mapToInt(Person::getAge).sum();System.out.println(sum2);Integer sum3 = userList.stream().collect(Collectors.summingInt(Person::getAge));System.out.println(sum3);System.out.println("最大值");Optional<Integer> max1 = userList.stream().map(Person::getAge).collect(Collectors.toList()).stream().reduce((v1, v2) -> v1 > v2 ? v1 : v2);System.out.println(max1.get());Optional<Integer> max2 = userList.stream().map(Person::getAge).collect(Collectors.toList()).stream().reduce(Integer::max);System.out.println(max2.get());int max3 = userList.stream().mapToInt(Person::getAge).max().getAsInt();System.out.println(max3);System.out.println("最小值");Optional<Integer> min = userList.stream().map(Person::getAge).collect(Collectors.toList()).stream().reduce(Integer::min);System.out.println(min.get());int min2 = userList.stream().mapToInt(Person::getAge).min().getAsInt();System.out.println(min2);System.out.println("平均值");Double averaging1 = userList.stream().collect(Collectors.averagingDouble(Person::getAge));System.out.println(averaging1);double averaging2 = userList.stream().mapToInt(Person::getAge).average().getAsDouble();System.out.println(averaging2);}
}
class Person{private String name;private int age;public Person(String name, int age) {this.name = name;this.age = age;}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;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", age=" + age +'}';}
}

mapToInt是 Stream API中一个非常有用的方法。它的主要作用是将一个 Stream 转换成一个IntStream,使得可以更加方便地对数字流进行处理。
IntStream中的一些常用方法如下:
- sum()
- max()
- min()
- average()
这些方法上面案例里面也有演示。
如果要操作的元素不是int,是double,我们也可以用mapToDouble也行。
package com.liudashuai;import java.util.ArrayList; import java.util.List;public class Test {public static void main(String[] args) {List<Person> userList = new ArrayList<>();userList.add(new Person("段誉",161.5));userList.add(new Person("萧峰",171.2));userList.add(new Person("虚竹",167.2));userList.add(new Person("无涯子",184.2));userList.add(new Person("慕容复",178.0));double sum = userList.stream().mapToDouble(Person::getHeight).sum();//和double max = userList.stream().mapToDouble(Person::getHeight).max().getAsDouble();//最高double min = userList.stream().mapToDouble(Person::getHeight).min().getAsDouble();//最矮double average = userList.stream().mapToDouble(Person::getHeight).average().getAsDouble();//平均System.out.println(sum);System.out.println(max);System.out.println(min);System.out.println(average);} } class Person{private String name;private double height;public Person(String name, double height) {this.name = name;this.height = height;}public String getName() {return name;}public void setName(String name) {this.name = name;}public double getHeight() {return height;}public void setHeight(double height) {this.height = height;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", height=" + height +'}';} }
统计(count/counting)
package com.liudashuai;import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;public class Test {public static void main(String[] args) {List<Person> userList = new ArrayList<>();userList.add(new Person("段誉",25));userList.add(new Person("萧峰",41));userList.add(new Person("虚竹",30));userList.add(new Person("无涯子",100));userList.add(new Person("虚竹",30));userList.add(new Person("慕容复",35));Long collect = userList.stream().filter(p -> p.getName() == "虚竹").collect(Collectors.counting());System.out.println(collect);long count = userList.stream().filter(p -> p.getAge() >= 50).count();System.out.println(count);}
}
class Person{private String name;private int age;public Person(String name, int age) {this.name = name;this.age = age;}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;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", age=" + age +'}';}
}

排序(sorted)
package com.liudashuai;import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;public class Test {public static void main(String[] args) {List<Person> userList = new ArrayList<>();userList.add(new Person("1",25));userList.add(new Person("2",41));userList.add(new Person("33",30));userList.add(new Person("11",100));userList.add(new Person("55",30));userList.add(new Person("22",35));List<Person> collect =userList.stream().sorted(Comparator.comparing(Person::getAge).reversed()).collect(Collectors.toList());System.out.println(collect);List<Person> collect2 =userList.stream().sorted(Comparator.comparing(Person::getAge)).collect(Collectors.toList());System.out.println(collect2);List<Person> collect3 =userList.stream().sorted(Comparator.comparing(Person::getName)).collect(Collectors.toList());System.out.println(collect3);List<Person> collect4 = userList.stream().sorted((e1, e2) -> {return Integer.compare(Integer.parseInt(e1.getName()), Integer.parseInt(e2.getName()));}).collect(Collectors.toList());System.out.println(collect4);}
}
class Person{private String name;private int age;public Person(String name, int age) {this.name = name;this.age = age;}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;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", age=" + age +'}';}
}

相关文章:
Java Stream 的常用API
Java Stream 的常用API 遍历(forEach) package com.liudashuai;import java.util.ArrayList; import java.util.List;public class Test {public static void main(String[] args) {List<Person> userList new ArrayList<>();userList.ad…...
代驾预约小程序系统源码 :提起预约,避免排队 带完整搭建教程
大家好啊,又到罗峰来给大家分享好用的源码系统的时间了。今天要给大家分享的第一款代驾预约小程序源码系统。传统的代驾服务中,用户往往需要在酒后代驾、长途驾驶等场景下,面对排队等待代驾司机空闲时间的繁琐过程。这不仅浪费了用户的时间和…...
es 报错 Data too large 触发断路器
文章目录 [toc]事出有因解决思路效果展示关于重启课外扩展 事出有因 报错原因是 es 在 full GC 之前触发了默认的断路器,导致报错 [parent] Data too large,相似的报错内容如下: Caused by: org.elasticsearch.common.breaker.CircuitBreakin…...
idea报[Ubuntu] File watcher failed repeatedly and has been disabled
1.安装File Watchers 2.restart idea解决...
phpstudy 开启目录浏览功能
(1)在该目录下: (2)选择对应网站的配置文件; (3)修改: # Options FollowSymLinks ExecCGI Options Indexes FollowSymLinks ExecCGI...
【前端开发】图例宽度根据数值自适应
前端开发 先看结果图 图例的宽度会随数值的改变而变化。 HTML部分 <!-- 数值部分 --> <ul class"tuli" ref"num"><listyle"margin-top: 5px;padding: 0 5px;text-align: center;"v-for"item of itemArr":key"i…...
AOMedia发布免版税沉浸音频规范IAMF
11月10日,开放媒体联盟(AOMedia)发布了旗下首个沉浸式音频规范IAMF(https://aomediacodec.github.io/iamf/),IAMF是一种编解码器无关的容器规范,可以携带回放时间渲染算法和音频混音的信息&…...
Linux C 进程编程
进程编程 进程介绍进程的定义进程和线程以及程序的区别进程块PCB进程的状态相关指令 进程调度算法先来先服务调度算法 FCFS短作业(进程)优先调度算法 SJF优先权调度算法 FPF优先权调度算法的类型非抢占式优先权算法抢占式优先权算法 优先权类型静态优先权动态优先权 高响应比优…...
Spring Boot (三)
1、热部署 热部署可以替我们节省大把花在重启项目本身上的时间。热部署原理上,一个springboot项目在运行时实际上是分两个过程进行的,根据加载的东西不同,划分成base类加载器与restart类加载器。 base类加载器:用来加载jar包中的类…...
第五章:抽象类
系列文章目录 文章目录 系列文章目录前言一、抽象类二、模板设计模式总结 前言 当我们想让子类来实现方法时,我们需要抽象类与抽象方法。 一、抽象类 当父类的某些方法,需要声明,但是又不确定如何实现时,可以将其声明为抽象方法…...
NSSCTF web刷题记录5
文章目录 [HZNUCTF 2023 preliminary]ezlogin[MoeCTF 2021]地狱通讯[NSSRound#7 Team]0o0[ISITDTU 2019]EasyPHP[极客大挑战 2020]greatphp[安洵杯 2020]Validator[GKCTF 2020]ez三剑客-ezweb [HZNUCTF 2023 preliminary]ezlogin 考点:时间盲注 打开题目,…...
Spark SQL 每年的1月1日算当年的第一个自然周, 给出日期,计算是本年的第几周
一、问题 按每年的1月1日算当年的第一个自然周 (遇到跨年也不管,如果1月1日是周三,那么到1月5号(周日)算是本年的第一个自然周, 如果按周一是一周的第一天) 计算是本年的第几周,那么 spark sql 如何写 ? 二、分析 …...
WebSocket Day04 : 消息推送
前言 随着Web应用程序的不断发展,实时性和交互性成为了用户体验中至关重要的一部分。传统的HTTP协议在处理实时数据传输方面存在一些局限性,而WebSocket作为一种全双工通信协议,为实现实时、高效的消息推送提供了全新的解决方案。 在Web开发…...
【Hadoop】MapReduce详解
🦄 个人主页——🎐开着拖拉机回家_大数据运维-CSDN博客 🎐✨🍁 🪁🍁🪁🍁🪁🍁🪁🍁 🪁🍁🪁…...
ctf之流量分析学习
链接:https://pan.baidu.com/s/1e3ZcfioIOmebbUs-xGRnUA?pwd9jmc 提取码:9jmc 前几道比较简单,是经常见、常考到的类型 1.pcap——zip里 流量分析里有压缩包 查字符串或者正则表达式,在包的最底层找到flag的相关内容 我们追踪…...
Linux——vim简介、配置方案(附带超美观的配置方案)、常用模式的基本操作
vim简介、配置方案、常用模式的基本操作 本章思维导图: 注:本章思维导图对应的xmind和.png文件都已同步导入至资源 1. vim简介 vim是Linux常用的文本编辑器,每个Linux账户都独有一个vim编辑器 本篇我们介绍vim最常用的三种模式:…...
在线预览编辑PDF::RAD PDF for ASP.NET
RAD PDF for ASP.NET作为功能最齐全的基于 HTML 的 PDF 查看器、编辑器和 ASP.NET 表单填充器,RAD PDF 为传统 PDF 解决方案提供了灵活而强大的替代方案。与 Adobe Acrobat Reader 不同,RAD PDF 几乎可以在任何现代网络浏览器中运行,…...
【赠书第4期】机器学习与人工智能实战:基于业务场景的工程应用
文章目录 前言 1 机器学习基础知识 2 人工智能基础知识 3 机器学习和人工智能的实战案例 4 总结 5 推荐图书 6 粉丝福利 前言 机器学习与人工智能是当前最热门的领域之一,也是未来发展的方向。随着科技的不断进步,越来越多的企业开始关注和投入机…...
npm封装插件打包上传后图片资源错误
问题: npm封装插件:封装的组件页面涉及使用图片资源,在封装的项目里调用图片显示正常;但是打包上传后,其他项目引入使用报错找不到图片资源;图片路径也不对 获取图片的base64方法 解决方案: 将…...
[云原生案例2.3 ] Kubernetes的部署安装 【多master集群架构高可用 ---- (二进制安装部署)】
文章目录 1. Kubernetes多Master集群高可用方案1.1 多节点Master高可用的实现过程1.2 实现高可用方法 2. 新Master节点的部署2.1 前置准备2.2 系统初始化操作2.2.1 关闭防火墙、selinux和swap分区2.2.2 修改主机名,添加域名映射2.2.3 修改内核参数2.2.4 时间同步 2.…...
数字IC时序约束实战:深入解析clock_uncertainty的设置策略与后端影响
1. 时钟不确定度的本质与组成 刚入行数字IC设计时,我最头疼的就是时序约束里那些看似相似却又微妙差别的概念。记得第一次看到clock_uncertainty这个参数,我盯着综合报告里的红色违例发了半小时呆。后来才明白,这个参数就像给时钟信号加了&qu…...
Krita 5.3.0 与 6.0.0 发布:功能升级与技术革新
文本与工具革新,Krita 功能升级Krita 5.3.0 和 6.0.0 正式推出,带来了一系列显著的功能改进。文本工具被完全重写,支持在画布上进行所见即所得编辑,还能支持 OpenType 的所有特性以及文本置入形状,这大大提升了文字处理…...
【Java外部函数性能优化黄金法则】:20年JVM专家亲授JNI/FFM调优的7大致命误区与3步极速修复方案
第一章:Java外部函数优化的演进脉络与性能本质Java平台对外部函数调用(Foreign Function & Memory API,即JEP 454/464/471/472)的演进,标志着JVM从“纯Java世界”迈向系统级互操作的新纪元。其性能本质并非单纯降低…...
赛美特冲刺港股:年营收7亿,刚完成8亿融资,估值73亿
雷递网 雷建平 3月31日赛美特信息集团股份有限公司(简称:“赛美特”)日前更新招股书,准备在港交所上市。赛美特成立以来获得多次融资,其中,2023年4月完成2.33亿元融资,投后估值62.33亿ÿ…...
【数字电路】从双稳态到触发器:时序逻辑的存储基石
1. 数字世界的记忆细胞:双稳态电路探秘 当你按下电脑电源键的瞬间,数十亿个微型存储单元开始工作,它们就像数字世界的记忆细胞,忠实地记录着每一个比特的信息。这一切的起点,正是我们今天要探讨的双稳态电路。想象一下…...
实战派指南:用MaPLe思路优化你的CLIP下游任务,附关键配置与避坑建议
实战派指南:用MaPLe思路优化你的CLIP下游任务,附关键配置与避坑建议 当CLIP遇上业务场景,90%的开发者都会遇到相同的问题:模型在新类别上的表现总是不尽如人意。上周团队用默认参数跑跨模态检索任务时,基类准确率82%的…...
Phi-4-mini-reasoning推理模型5分钟快速上手:数学题逻辑题一键解答
Phi-4-mini-reasoning推理模型5分钟快速上手:数学题逻辑题一键解答 1. 为什么选择Phi-4-mini-reasoning? 如果你经常需要解决数学题、逻辑题或者需要一步步分析的问题,Phi-4-mini-reasoning就是为你量身定制的AI助手。这个模型不像那些通用…...
从拆解到驱动:手把手教你用IMX6ULL驱动OV5640摄像头模块(附完整代码)
从拆解到驱动:手把手教你用IMX6ULL驱动OV5640摄像头模块(附完整代码) 1. 硬件连接与接口解析 OV5640作为一款500万像素的CMOS图像传感器,支持DVP和MIPI两种接口模式。在IMX6ULL平台上,我们选择使用DVP并行接口进行连接…...
高效低成本馈电保护电路设计与应用
1. 为什么需要馈电保护电路? 有源天线在通信系统中扮演着重要角色,但实际使用中经常会遇到一些棘手的问题。比如在野外作业时,技术人员可能会频繁插拔天线;或者在长期运行过程中,天线内部电路可能出现故障。这些情况都…...
STM32F4读写SD卡:填一填ST官方HAL库的坑
使用STM32读写SD卡在低功耗存储中的应用是比较常见的,但是网上大多数资料都是基于标准库或者基于寄存器的开发。随着嵌入式设备越来越复杂,使用HAL库能够大大降低开发者的学习成本,从而提高开发效率。近年来,ST官方主推以STM32Cub…...

