当前位置: 首页 > news >正文

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 +'}';}
}

在这里插入图片描述

  1. findFirst() 方法根据命名,我们可以大致知道是获取Optional流中的第一个元素。
  2. 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中的一些常用方法如下:

  1. sum()
  2. max()
  3. min()
  4. 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 遍历&#xff08;forEach&#xff09; 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…...

代驾预约小程序系统源码 :提起预约,避免排队 带完整搭建教程

大家好啊&#xff0c;又到罗峰来给大家分享好用的源码系统的时间了。今天要给大家分享的第一款代驾预约小程序源码系统。传统的代驾服务中&#xff0c;用户往往需要在酒后代驾、长途驾驶等场景下&#xff0c;面对排队等待代驾司机空闲时间的繁琐过程。这不仅浪费了用户的时间和…...

es 报错 Data too large 触发断路器

文章目录 [toc]事出有因解决思路效果展示关于重启课外扩展 事出有因 报错原因是 es 在 full GC 之前触发了默认的断路器&#xff0c;导致报错 [parent] Data too large&#xff0c;相似的报错内容如下&#xff1a; Caused by: org.elasticsearch.common.breaker.CircuitBreakin…...

idea报[Ubuntu] File watcher failed repeatedly and has been disabled

1.安装File Watchers 2.restart idea解决...

phpstudy 开启目录浏览功能

&#xff08;1&#xff09;在该目录下&#xff1a; &#xff08;2&#xff09;选择对应网站的配置文件&#xff1b; &#xff08;3&#xff09;修改&#xff1a; # 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日&#xff0c;开放媒体联盟&#xff08;AOMedia&#xff09;发布了旗下首个沉浸式音频规范IAMF&#xff08;https://aomediacodec.github.io/iamf/&#xff09;&#xff0c;IAMF是一种编解码器无关的容器规范&#xff0c;可以携带回放时间渲染算法和音频混音的信息&…...

Linux C 进程编程

进程编程 进程介绍进程的定义进程和线程以及程序的区别进程块PCB进程的状态相关指令 进程调度算法先来先服务调度算法 FCFS短作业(进程)优先调度算法 SJF优先权调度算法 FPF优先权调度算法的类型非抢占式优先权算法抢占式优先权算法 优先权类型静态优先权动态优先权 高响应比优…...

Spring Boot (三)

1、热部署 热部署可以替我们节省大把花在重启项目本身上的时间。热部署原理上&#xff0c;一个springboot项目在运行时实际上是分两个过程进行的&#xff0c;根据加载的东西不同&#xff0c;划分成base类加载器与restart类加载器。 base类加载器&#xff1a;用来加载jar包中的类…...

第五章:抽象类

系列文章目录 文章目录 系列文章目录前言一、抽象类二、模板设计模式总结 前言 当我们想让子类来实现方法时&#xff0c;我们需要抽象类与抽象方法。 一、抽象类 当父类的某些方法&#xff0c;需要声明&#xff0c;但是又不确定如何实现时&#xff0c;可以将其声明为抽象方法…...

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 考点&#xff1a;时间盲注 打开题目&#xff0c…...

Spark SQL 每年的1月1日算当年的第一个自然周, 给出日期,计算是本年的第几周

一、问题 按每年的1月1日算当年的第一个自然周 (遇到跨年也不管&#xff0c;如果1月1日是周三&#xff0c;那么到1月5号&#xff08;周日&#xff09;算是本年的第一个自然周, 如果按周一是一周的第一天) 计算是本年的第几周&#xff0c;那么 spark sql 如何写 ? 二、分析 …...

WebSocket Day04 : 消息推送

前言 随着Web应用程序的不断发展&#xff0c;实时性和交互性成为了用户体验中至关重要的一部分。传统的HTTP协议在处理实时数据传输方面存在一些局限性&#xff0c;而WebSocket作为一种全双工通信协议&#xff0c;为实现实时、高效的消息推送提供了全新的解决方案。 在Web开发…...

【Hadoop】MapReduce详解

&#x1f984; 个人主页——&#x1f390;开着拖拉机回家_大数据运维-CSDN博客 &#x1f390;✨&#x1f341; &#x1fa81;&#x1f341;&#x1fa81;&#x1f341;&#x1fa81;&#x1f341;&#x1fa81;&#x1f341; &#x1fa81;&#x1f341;&#x1fa81;&#x1f…...

ctf之流量分析学习

链接&#xff1a;https://pan.baidu.com/s/1e3ZcfioIOmebbUs-xGRnUA?pwd9jmc 提取码&#xff1a;9jmc 前几道比较简单&#xff0c;是经常见、常考到的类型 1.pcap——zip里 流量分析里有压缩包 查字符串或者正则表达式&#xff0c;在包的最底层找到flag的相关内容 我们追踪…...

Linux——vim简介、配置方案(附带超美观的配置方案)、常用模式的基本操作

vim简介、配置方案、常用模式的基本操作 本章思维导图&#xff1a; 注&#xff1a;本章思维导图对应的xmind和.png文件都已同步导入至资源 1. vim简介 vim是Linux常用的文本编辑器&#xff0c;每个Linux账户都独有一个vim编辑器 本篇我们介绍vim最常用的三种模式&#xff1a;…...

在线预览编辑PDF::RAD PDF for ASP.NET

RAD PDF for ASP.NET作为功​​能最齐全的基于 HTML 的 PDF 查看器、编辑器和 ASP.NET 表单填充器&#xff0c;RAD PDF 为传统 PDF 解决方案提供了灵活而强大的替代方案。与 Adob​​e Acrobat Reader 不同&#xff0c;RAD PDF 几乎可以在任何现代网络浏览器中运行&#xff0c;…...

【赠书第4期】机器学习与人工智能实战:基于业务场景的工程应用

文章目录 前言 1 机器学习基础知识 2 人工智能基础知识 3 机器学习和人工智能的实战案例 4 总结 5 推荐图书 6 粉丝福利 前言 机器学习与人工智能是当前最热门的领域之一&#xff0c;也是未来发展的方向。随着科技的不断进步&#xff0c;越来越多的企业开始关注和投入机…...

npm封装插件打包上传后图片资源错误

问题&#xff1a; npm封装插件&#xff1a;封装的组件页面涉及使用图片资源&#xff0c;在封装的项目里调用图片显示正常&#xff1b;但是打包上传后&#xff0c;其他项目引入使用报错找不到图片资源&#xff1b;图片路径也不对 获取图片的base64方法 解决方案&#xff1a; 将…...

[云原生案例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 修改主机名&#xff0c;添加域名映射2.2.3 修改内核参数2.2.4 时间同步 2.…...

Cursor实现用excel数据填充word模版的方法

cursor主页&#xff1a;https://www.cursor.com/ 任务目标&#xff1a;把excel格式的数据里的单元格&#xff0c;按照某一个固定模版填充到word中 文章目录 注意事项逐步生成程序1. 确定格式2. 调试程序 注意事项 直接给一个excel文件和最终呈现的word文件的示例&#xff0c;…...

docker详细操作--未完待续

docker介绍 docker官网: Docker&#xff1a;加速容器应用程序开发 harbor官网&#xff1a;Harbor - Harbor 中文 使用docker加速器: Docker镜像极速下载服务 - 毫秒镜像 是什么 Docker 是一种开源的容器化平台&#xff0c;用于将应用程序及其依赖项&#xff08;如库、运行时环…...

Admin.Net中的消息通信SignalR解释

定义集线器接口 IOnlineUserHub public interface IOnlineUserHub {/// 在线用户列表Task OnlineUserList(OnlineUserList context);/// 强制下线Task ForceOffline(object context);/// 发布站内消息Task PublicNotice(SysNotice context);/// 接收消息Task ReceiveMessage(…...

理解 MCP 工作流:使用 Ollama 和 LangChain 构建本地 MCP 客户端

&#x1f31f; 什么是 MCP&#xff1f; 模型控制协议 (MCP) 是一种创新的协议&#xff0c;旨在无缝连接 AI 模型与应用程序。 MCP 是一个开源协议&#xff0c;它标准化了我们的 LLM 应用程序连接所需工具和数据源并与之协作的方式。 可以把它想象成你的 AI 模型 和想要使用它…...

高频面试之3Zookeeper

高频面试之3Zookeeper 文章目录 高频面试之3Zookeeper3.1 常用命令3.2 选举机制3.3 Zookeeper符合法则中哪两个&#xff1f;3.4 Zookeeper脑裂3.5 Zookeeper用来干嘛了 3.1 常用命令 ls、get、create、delete、deleteall3.2 选举机制 半数机制&#xff08;过半机制&#xff0…...

如何将联系人从 iPhone 转移到 Android

从 iPhone 换到 Android 手机时&#xff0c;你可能需要保留重要的数据&#xff0c;例如通讯录。好在&#xff0c;将通讯录从 iPhone 转移到 Android 手机非常简单&#xff0c;你可以从本文中学习 6 种可靠的方法&#xff0c;确保随时保持连接&#xff0c;不错过任何信息。 第 1…...

Nginx server_name 配置说明

Nginx 是一个高性能的反向代理和负载均衡服务器&#xff0c;其核心配置之一是 server 块中的 server_name 指令。server_name 决定了 Nginx 如何根据客户端请求的 Host 头匹配对应的虚拟主机&#xff08;Virtual Host&#xff09;。 1. 简介 Nginx 使用 server_name 指令来确定…...

HBuilderX安装(uni-app和小程序开发)

下载HBuilderX 访问官方网站&#xff1a;https://www.dcloud.io/hbuilderx.html 根据您的操作系统选择合适版本&#xff1a; Windows版&#xff08;推荐下载标准版&#xff09; Windows系统安装步骤 运行安装程序&#xff1a; 双击下载的.exe安装文件 如果出现安全提示&…...

IT供电系统绝缘监测及故障定位解决方案

随着新能源的快速发展&#xff0c;光伏电站、储能系统及充电设备已广泛应用于现代能源网络。在光伏领域&#xff0c;IT供电系统凭借其持续供电性好、安全性高等优势成为光伏首选&#xff0c;但在长期运行中&#xff0c;例如老化、潮湿、隐裂、机械损伤等问题会影响光伏板绝缘层…...

css3笔记 (1) 自用

outline: none 用于移除元素获得焦点时默认的轮廓线 broder:0 用于移除边框 font-size&#xff1a;0 用于设置字体不显示 list-style: none 消除<li> 标签默认样式 margin: xx auto 版心居中 width:100% 通栏 vertical-align 作用于行内元素 / 表格单元格&#xff…...