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

stm32G473的flash模式是单bank还是双bank?

今天突然有人stm32G473的flash模式是单bank还是双bank&#xff1f;由于时间太久&#xff0c;我真忘记了。搜搜发现&#xff0c;还真有人和我一样。见下面的链接&#xff1a;https://shequ.stmicroelectronics.cn/forum.php?modviewthread&tid644563 根据STM32G4系列参考手…...

深入理解JavaScript设计模式之单例模式

目录 什么是单例模式为什么需要单例模式常见应用场景包括 单例模式实现透明单例模式实现不透明单例模式用代理实现单例模式javaScript中的单例模式使用命名空间使用闭包封装私有变量 惰性单例通用的惰性单例 结语 什么是单例模式 单例模式&#xff08;Singleton Pattern&#…...

在四层代理中还原真实客户端ngx_stream_realip_module

一、模块原理与价值 PROXY Protocol 回溯 第三方负载均衡&#xff08;如 HAProxy、AWS NLB、阿里 SLB&#xff09;发起上游连接时&#xff0c;将真实客户端 IP/Port 写入 PROXY Protocol v1/v2 头。Stream 层接收到头部后&#xff0c;ngx_stream_realip_module 从中提取原始信息…...

css的定位(position)详解:相对定位 绝对定位 固定定位

在 CSS 中&#xff0c;元素的定位通过 position 属性控制&#xff0c;共有 5 种定位模式&#xff1a;static&#xff08;静态定位&#xff09;、relative&#xff08;相对定位&#xff09;、absolute&#xff08;绝对定位&#xff09;、fixed&#xff08;固定定位&#xff09;和…...

HTML前端开发:JavaScript 常用事件详解

作为前端开发的核心&#xff0c;JavaScript 事件是用户与网页交互的基础。以下是常见事件的详细说明和用法示例&#xff1a; 1. onclick - 点击事件 当元素被单击时触发&#xff08;左键点击&#xff09; button.onclick function() {alert("按钮被点击了&#xff01;&…...

【JavaSE】绘图与事件入门学习笔记

-Java绘图坐标体系 坐标体系-介绍 坐标原点位于左上角&#xff0c;以像素为单位。 在Java坐标系中,第一个是x坐标,表示当前位置为水平方向&#xff0c;距离坐标原点x个像素;第二个是y坐标&#xff0c;表示当前位置为垂直方向&#xff0c;距离坐标原点y个像素。 坐标体系-像素 …...

图表类系列各种样式PPT模版分享

图标图表系列PPT模版&#xff0c;柱状图PPT模版&#xff0c;线状图PPT模版&#xff0c;折线图PPT模版&#xff0c;饼状图PPT模版&#xff0c;雷达图PPT模版&#xff0c;树状图PPT模版 图表类系列各种样式PPT模版分享&#xff1a;图表系列PPT模板https://pan.quark.cn/s/20d40aa…...

CSS设置元素的宽度根据其内容自动调整

width: fit-content 是 CSS 中的一个属性值&#xff0c;用于设置元素的宽度根据其内容自动调整&#xff0c;确保宽度刚好容纳内容而不会超出。 效果对比 默认情况&#xff08;width: auto&#xff09;&#xff1a; 块级元素&#xff08;如 <div>&#xff09;会占满父容器…...

Java求职者面试指南:Spring、Spring Boot、MyBatis框架与计算机基础问题解析

Java求职者面试指南&#xff1a;Spring、Spring Boot、MyBatis框架与计算机基础问题解析 一、第一轮提问&#xff08;基础概念问题&#xff09; 1. 请解释Spring框架的核心容器是什么&#xff1f;它在Spring中起到什么作用&#xff1f; Spring框架的核心容器是IoC容器&#…...

浪潮交换机配置track检测实现高速公路收费网络主备切换NQA

浪潮交换机track配置 项目背景高速网络拓扑网络情况分析通信线路收费网络路由 收费汇聚交换机相应配置收费汇聚track配置 项目背景 在实施省内一条高速公路时遇到的需求&#xff0c;本次涉及的主要是收费汇聚交换机的配置&#xff0c;浪潮网络设备在高速项目很少&#xff0c;通…...