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

在这里插入图片描述

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

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

相关文章

杭电oj 2035 人见人爱A^B C语言

#include<stdio.h>void main() {int a, b, i,num;while (~scanf_s("%d%d", &a, &b) && (a ! 0 || b ! 0)){num a;for (i 1; i < b; i){num * a;num % 1000;}printf("%d\n", num);} }

Clickhouse学习笔记

学习内容参考&#xff1a;一套上手ClickHouse-OLAP分析引擎&#xff0c;囊括Prometheus与Grafana_哔哩哔哩_bilibili 下为笔记链接&#xff0c;以及全套笔记pdf版本 Clickhouse学习笔记&#xff08;1&#xff09;—— ClickHouse的安装启动_clickhouse后台启动_THE WHY的博客-C…

使用Filebeat+Kafka+Logstash+Elasticsearch构建日志分析系统

随着时间的积累&#xff0c;日志数据会越来越多&#xff0c;当您需要查看并分析庞杂的日志数据时&#xff0c;可通过FilebeatKafkaLogstashElasticsearch采集日志数据到Elasticsearch中&#xff0c;并通过Kibana进行可视化展示与分析。本文介绍具体的实现方法。 一、背景信息 …

C语言不可不敲系列:跳水比赛排名问题

目录 1题干&#xff1a; 2解题思路&#xff1a; 3代码: 4运行结果: 5总结: 1题干&#xff1a; 5位运动员参加了10米台跳水比赛&#xff0c;有人让他们预测比赛结果 A选手说&#xff1a;B第二&#xff0c;我第三&#xff1b; B选手说&#xff1a;我第二&#xff0c;E第四&am…

【LeetCode刷题-滑动窗口】--1456.定长子串中元音的最大数目

1456.定长子串中元音的最大数目 方法&#xff1a;使用滑动窗口 class Solution {public int maxVowels(String s, int k) {int n s.length();int sum 0;for(int i 0;i<k;i){sum isVowel(s.charAt(i));}int ans sum;for(int i k;i<n;i){sum sum isVowel(s.charAt…

MHA实验和架构

什么是MHA&#xff1f; masterhight availabulity&#xff1a;基于主库的高可用环境下可以实现主从复制、故障切换 MHA的主从架构最少要一主两从 MHA的出现是为了解决MySQL的单点故障问题。一旦主库崩溃&#xff0c;MHA可以在0-30秒内自动完成故障切换。 MHA的数据流向和工…

钡铼技术4G RTU采集器在智慧农业灌溉控制中的使用介绍

随着科技的不断发展&#xff0c;智慧农业已经成为现代农业发展的重要方向之一。在智慧农业中&#xff0c;灌溉控制是至关重要的环节&#xff0c;而4G RTU采集器作为一种先进的数据采集设备&#xff0c;为智慧农业灌溉控制提供了全新的解决方案。本文将就钡铼技术有限公司的4G R…

JWT概念(登录代码实现)

JWT (JSON Web Token)是一种开放标准&#xff0c;用于在网络应用程序之间安全地传输信息。JWT是一种基于JSON的轻量级令牌&#xff0c;包含了一些声明和签名&#xff0c;可以用于认证和授权。 JWT主要由三部分组成&#xff1a;头部、载荷和签名。 头部包含了使用的算法和类型…

算法--搜索与图

这里写目录标题 主要内容DFS思想 BFS思想 DFS与BFS的比较一级目录二级目录二级目录二级目录 一级目录二级目录二级目录二级目录 一级目录二级目录二级目录二级目录 主要内容 DFS 思想 会优先向深处搜索 一旦到达最深处 那么会回溯 但是在回溯的过程中 会边回溯边观察是否有能继…

P1260 工程规划

工程规划 题目描述 造一幢大楼是一项艰巨的工程&#xff0c;它是由 n n n 个子任务构成的&#xff0c;给它们分别编号 1 , 2 , ⋯ , n ( 5 ≤ n ≤ 1000 ) 1,2,\cdots,n\ (5≤n≤1000) 1,2,⋯,n (5≤n≤1000)。由于对一些任务的起始条件有着严格的限制&#xff0c;所以每个…

武汉凯迪正大—锂电池均衡维护仪

产品概况 KDZD885C 电池容量平衡测试系统&#xff0c;主要用于锂电池箱充放电测试及均衡维护&#xff0c;解决锂电池包单芯电压不均衡的痛点&#xff0c;用于快速解决锂电池电压不一致的难题,适用于各锂电池模组电压等级&#xff0c;集单芯放电&#xff0c;充电&#xff0c;均…

linux openlab搭建web网站

网站需求&#xff1a; 1.基于域名 www.openlab.com 可以访问网站内容为 welcome to openlab!!! 2.给该公司创建三个子界面分别显示学生信息&#xff0c;教学资料和缴费网站&#xff0c; 1、基于 www.openlab.com/student 网站访问学生信息&#xff0c; 2、基于 www.openlab…

Chrome版本对应Selenium版本

1.获得浏览器版本号和驱动 浏览器版本: 119.0.6045.124 浏览器驱动版本: 119.0.6043.1 / 120.0.6051.0 访问 https://vikyd.github.io/download-chromium-history-version/ 2. 安装selenium pip install selenium4.1.1 -i http://pypi.mirrors.ustc.edu.cn/simple/ --trusted…

DAY53 1143.最长公共子序列 + 1035.不相交的线 + 53. 最大子序和

1143.最长公共子序列 题目要求&#xff1a;给定两个字符串 text1 和 text2&#xff0c;返回这两个字符串的最长公共子序列的长度。 一个字符串的 子序列 是指这样一个新的字符串&#xff1a;它是由原字符串在不改变字符的相对顺序的情况下删除某些字符&#xff08;也可以不删…

记录:unity脚本的编写6.0

目录 unity UI系统添加ui编写脚本 unity UI系统 在日常的游戏或者别的什么活动中&#xff0c;ui总是必不可少的一项&#xff0c;在java中也有关于GUI的内容&#xff0c;unity也不例外&#xff0c;这次就使用脚本控制在unity添加的各种ui组件&#xff0c;使他们可以完成一些我们…

MTK手机平台充电原理

EPT GPIO初始化文件 bsp_gpio_ept_config.c 1 知识点总结 1.1 Official 参考充电电路 Figure 1-1 参考电路 VCHG&#xff1a;USB正极 VCDT&#xff1a;VCHG Charger Detect充电电压检测脚 ISENSE&#xff1a;充电电流检测电阻的正极 BATSNS&#xff1a;充电电流检测电阻的负极 …

桌面云架构讲解(VDI、IDV、VOI/TCI、RDS)

目录 云桌面架构 VDI 虚拟桌面基础架构 IDV 智能桌面虚拟化 VOI/TCI VOI 虚拟系统架构 TCI 透明计算机架构 RDS 远程桌面服务 不同厂商云桌面架构 桌面传输协议 什么是云桌面 桌面云是虚拟化技术成熟后发展起来的一种应用&#xff0c;桌面云通常也称为云桌面、VDI等 …

kubernetes-ingress处理路由路径

aliyun相关文档 配置URL重定向的路由服务 当使用Nginx Ingress Controller的时候&#xff0c;Nginx会将路径完整转发到后端&#xff08;如&#xff0c;从Ingress访问的/service1/api路径会直接转发到后端Pod的/service1/api/路径&#xff09;。如果您后端的服务路径为/api&am…

Selenium+JQuery定位方法及应用

SeleniumJQuery定位方法及应用 1 JQuery定位说明1.1 JQuery定位方法1.2 JQuery最常用的三个操作1.3 JQuery一个示例1.3.1 用户名输入框1.3.2 密码输入框1.3.3 登陆按钮1.3.4 完整代码 2 JQuery选择器2.1 常用选择器列表2.2 思考 1、关于Selenium提供了很多元素定位方法&#xf…

Mybatis-Plus条件构造器QueryWrapper

Mybatis-Plus条件构造器QueryWrapper 1、条件构造器关系介绍 介绍 &#xff1a; 上图绿色框为抽象类 蓝色框为正常类&#xff0c;可创建对象 黄色箭头指向为父子类关系&#xff0c;箭头指向为父类 wapper介绍 &#xff1a; Wrapper &#xff1a; 条件构造抽象类&#xff0…