当前位置: 首页 > 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.…...

Linux链表操作全解析

Linux C语言链表深度解析与实战技巧 一、链表基础概念与内核链表优势1.1 为什么使用链表&#xff1f;1.2 Linux 内核链表与用户态链表的区别 二、内核链表结构与宏解析常用宏/函数 三、内核链表的优点四、用户态链表示例五、双向循环链表在内核中的实现优势5.1 插入效率5.2 安全…...

shell脚本--常见案例

1、自动备份文件或目录 2、批量重命名文件 3、查找并删除指定名称的文件&#xff1a; 4、批量删除文件 5、查找并替换文件内容 6、批量创建文件 7、创建文件夹并移动文件 8、在文件夹中查找文件...

线程同步:确保多线程程序的安全与高效!

全文目录&#xff1a; 开篇语前序前言第一部分&#xff1a;线程同步的概念与问题1.1 线程同步的概念1.2 线程同步的问题1.3 线程同步的解决方案 第二部分&#xff1a;synchronized关键字的使用2.1 使用 synchronized修饰方法2.2 使用 synchronized修饰代码块 第三部分&#xff…...

vscode(仍待补充)

写于2025 6.9 主包将加入vscode这个更权威的圈子 vscode的基本使用 侧边栏 vscode还能连接ssh&#xff1f; debug时使用的launch文件 1.task.json {"tasks": [{"type": "cppbuild","label": "C/C: gcc.exe 生成活动文件"…...

Python爬虫实战:研究feedparser库相关技术

1. 引言 1.1 研究背景与意义 在当今信息爆炸的时代,互联网上存在着海量的信息资源。RSS(Really Simple Syndication)作为一种标准化的信息聚合技术,被广泛用于网站内容的发布和订阅。通过 RSS,用户可以方便地获取网站更新的内容,而无需频繁访问各个网站。 然而,互联网…...

linux 错误码总结

1,错误码的概念与作用 在Linux系统中,错误码是系统调用或库函数在执行失败时返回的特定数值,用于指示具体的错误类型。这些错误码通过全局变量errno来存储和传递,errno由操作系统维护,保存最近一次发生的错误信息。值得注意的是,errno的值在每次系统调用或函数调用失败时…...

三体问题详解

从物理学角度&#xff0c;三体问题之所以不稳定&#xff0c;是因为三个天体在万有引力作用下相互作用&#xff0c;形成一个非线性耦合系统。我们可以从牛顿经典力学出发&#xff0c;列出具体的运动方程&#xff0c;并说明为何这个系统本质上是混沌的&#xff0c;无法得到一般解…...

CVE-2020-17519源码分析与漏洞复现(Flink 任意文件读取)

漏洞概览 漏洞名称&#xff1a;Apache Flink REST API 任意文件读取漏洞CVE编号&#xff1a;CVE-2020-17519CVSS评分&#xff1a;7.5影响版本&#xff1a;Apache Flink 1.11.0、1.11.1、1.11.2修复版本&#xff1a;≥ 1.11.3 或 ≥ 1.12.0漏洞类型&#xff1a;路径遍历&#x…...

基于Java+MySQL实现(GUI)客户管理系统

客户资料管理系统的设计与实现 第一章 需求分析 1.1 需求总体介绍 本项目为了方便维护客户信息为了方便维护客户信息&#xff0c;对客户进行统一管理&#xff0c;可以把所有客户信息录入系统&#xff0c;进行维护和统计功能。可通过文件的方式保存相关录入数据&#xff0c;对…...

【分享】推荐一些办公小工具

1、PDF 在线转换 https://smallpdf.com/cn/pdf-tools 推荐理由&#xff1a;大部分的转换软件需要收费&#xff0c;要么功能不齐全&#xff0c;而开会员又用不了几次浪费钱&#xff0c;借用别人的又不安全。 这个网站它不需要登录或下载安装。而且提供的免费功能就能满足日常…...