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

Stream流的常用方法(自用)

自用的笔记, 有🚩 需要多看

基本数据

自定义实体

@Data
class Student{private String name;private Integer age;private Double height;public Student() {}
}

假数据

Student s1 = new Student();
s1.setAge(20);
s1.setName("cookie");
s1.setHeight(180d);Student s2 = new Student();
s2.setAge(30);
s2.setName("cookie");
s2.setHeight(180d);Student s3 = new Student();
s3.setAge(40);
s3.setName("bob");
s3.setHeight(175d);Student s4 = new Student();
s4.setAge(40);
s4.setName("bob");
s4.setHeight(180d);// 存入list集合
List<Student> list = new ArrayList<>();
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);

一, 分组

1. 一层分组/简单分组

/*** 需求一(一层分组):根据Age分组*/
System.out.println("需求一(一层分组):根据Age分组");
Map<Integer, List<Student>> collect = list.stream().collect(Collectors.groupingBy(Student::getAge));
for (Integer age : collect.keySet()) {System.out.println("key:" + age + "\tvalue:" + collect.get(age));
}/*** 控制台结果:* key:20	value:[Student(name=cookie, age=20, height=180.0)]* key:40	value:[Student(name=bob, age=40, height=175.0), Student(name=bob, age=40, height=180.0)]* key:30	value:[Student(name=cookie, age=30, height=180.0)]*/

2. 多层分组

/*** 需求二: 先根据name分组,然后再根据身高分组*/
System.out.println("需求二: 先根据name分组,然后再根据身高分组");
Map<String, Map<Double, List<Student>>> collect1 = list.stream().collect(Collectors.groupingBy(Student::getName, Collectors.groupingBy(Student::getHeight)));
Set<String> namesGroup = collect1.keySet();
for (String namekey : namesGroup) {Map<Double, List<Student>> heightGroupMap = collect1.get(namekey);Set<Double> height = heightGroupMap.keySet();for (Double h : height) {System.out.println("name:" + namekey + " height:" + heightGroupMap.get(h));}
}/*** 控制台结果:* name:bob height:[Student(name=bob, age=40, height=175.0)]* name:bob height:[Student(name=bob, age=40, height=180.0)]* name:cookie height:[Student(name=cookie, age=20, height=180.0), Student(name=cookie, age=30, height=180.0)]*/

3. 多层分组-自定义key 🚩

/*** 需求三: 自定义key返回 形式如下: age_height bob_175*/
System.out.println("需求三: 自定义key返回 形式如下: age_height bob_175");
Map<String, List<Student>> collect2 = list.stream().collect(Collectors.groupingBy(c -> c.getName() + "_" + c.getHeight()));for (String customKey : collect2.keySet()) {System.out.println("key:" + customKey +" value:"+ collect2.get(customKey));
}
/*** 控制台结果:* key:bob_180.0 value:[Student(name=bob, age=40, height=180.0)]* key:bob_175.0 value:[Student(name=bob, age=40, height=175.0)]* key:cookie_180.0 value:[Student(name=cookie, age=20, height=180.0), Student(name=cookie, age=30, height=180.0)]*/

二, 排序

方式一: 通过自定义的比较器(非必要不推荐)

/**
* 需求: 根据身高排序,如果身高相同,根据年龄排序,如果年龄依然相同,根据名称字母顺序排序
*/
List<Student> collect3 = list.stream().sorted(new Comparator<Student>() {@Overridepublic int compare(Student o1, Student o2) {// 这里前面的减去后面的是升序, 反之这是降序if (!o1.getHeight().equals(o2.getHeight())) {return (int) (o1.getHeight() - o2.getHeight());}if (!o1.getAge().equals(o2.getAge())) {return o1.getAge() - o2.getAge();}return o1.getName().compareTo(o2.getName());}
}).collect(Collectors.toList());
System.out.println(collect3);/*** 控制台结果:* [Student(name=bob, age=40, height=175.0), * Student(name=cookie, age=20, height=180.0), * Student(name=cookie, age=30, height=180.0), * Student(name=bob, age=40, height=180.0)]*/// 注: 当然上面的也可以做一个简化
List<Student> collect3 = list.stream().sorted((o1, o2) -> {// 这里前面的减去后面的是升序, 反之这是降序if (!o1.getHeight().equals(o2.getHeight())) {return (int) (o1.getHeight() - o2.getHeight());}if (!o1.getAge().equals(o2.getAge())) {return o1.getAge() - o2.getAge();}return o1.getName().compareTo(o2.getName());
}).collect(Collectors.toList());

方式二: 通过lambda 🚩

List<Student> collect4 = list.stream().sorted(Comparator.comparingDouble(Student::getHeight).thenComparingInt(Student::getAge).thenComparing(Student::getName)).collect(Collectors.toList());
System.out.println(collect4);/*** 控制台结果:* [Student(name=bob, age=40, height=175.0), * Student(name=cookie, age=20, height=180.0), * Student(name=cookie, age=30, height=180.0), * Student(name=bob, age=40, height=180.0)]*/// 注意:
// 方式一,升序降序是通过返回的正负, 
// 方式二而是通过方法, 现在我们首先通过身高降序, 我们只需要在条件的后面加一个reversed()后缀方法即可List<Student> collect4 = list.stream().sorted(Comparator.comparingDouble(Student::getHeight).reversed().thenComparingInt(Student::getAge).thenComparing(Student::getName)
).collect(Collectors.toList());
System.out.println(collect4);/*** 修改之后控制台结果:* [Student(name=cookie, age=20, height=180.0), * Student(name=cookie, age=30, height=180.0), * Student(name=bob, age=40, height=180.0), * Student(name=bob, age=40, height=175.0)]*/

三, 统计

/*** 需求: 统计年龄之和*/
int ageSum = list.stream().mapToInt(Student::getAge).sum();/*** 求年龄平均值*/
Double ageAvg1 = list.stream().collect(Collectors.averagingInt(Student::getAge));
// 或者
double ageAvg2 = list.stream().mapToInt(Student::getAge).average().getAsDouble();/*** 求年龄最大值*/
int maxAge = list.stream().mapToInt(Student::getAge).max().getAsInt();/*** 最小值*/
int minAge = list.stream().mapToInt(Student::getAge).min().getAsInt();

缓慢总结中~~~~

相关文章:

Stream流的常用方法(自用)

自用的笔记, 有&#x1f6a9; 需要多看 基本数据 自定义实体 Data class Student{private String name;private Integer age;private Double height;public Student() {} }假数据 Student s1 new Student(); s1.setAge(20); s1.setName("cookie"); s1.setHeight(…...

【python函数】torch.nn.Embedding函数用法图解

学习SAM模型的时候&#xff0c;第一次看见了nn.Embedding函数&#xff0c;以前接触CV比较多&#xff0c;很少学习词嵌入方面的&#xff0c;找了一些资料一开始也不是很理解&#xff0c;多看了两遍后&#xff0c;突然顿悟&#xff0c;特此记录。 SAM中PromptEncoder中运用nn.Emb…...

with ldid... /opt/MonkeyDev/bin/md: line 326: ldid: command not found

吐槽傻逼xcode 根据提示 执行了这个脚本/opt/MonkeyDev/bin/md 往这里面添加你brew install 安装文件的目录即可...

[golang gui]fyne框架代码示例

1、下载GO Go语言中文网 golang安装包 - 阿里镜像站(镜像站使用方法&#xff1a;查找最新非rc版本的golang安装包) golang安装包 - 中科大镜像站 go二进制文件下载 - 南京大学开源镜像站 Go语言官网(Google中国) Go语言官网(Go团队) 截至目前&#xff08;2023年9月17日&#x…...

2000-2018年各省能源消费和碳排放数据

2000-2018年各省能源消费和碳排放数据 1、时间&#xff1a;2000-2018年 2、范围&#xff1a;30个省市 3、指标&#xff1a;id、year、ENERGY、COAL、碳排放倒数*100 4、来源&#xff1a;能源年鉴 5、指标解释&#xff1a; 2018年碳排放和能源数据为插值法推算得到 碳排放…...

C# ref 学习1

ref 关键字用在四种不同的上下文中&#xff1b; 1.在方法签名和方法调用中&#xff0c;按引用将参数传递给方法。 2.在方法签名中&#xff0c;按引用将值返回给调用方。 3.在成员正文中&#xff0c;指示引用返回值是否作为调用方欲修改的引用被存储在本地&#xff0c;或在一般…...

MQ - 08 基础篇_消费者客户端SDK设计(下)

文章目录 导图Pre概述消费分组协调者消费分区分配策略轮询粘性自定义消费确认确认后删除数据确认后保存消费进度数据消费失败处理从服务端拉取数据失败本地业务数据处理失败提交位点信息失败总结导图 Pre...

Flutter层对于Android 13存储权限的适配问题

感觉很久没有写博客了&#xff0c;不对&#xff0c;的确是很久没有写博客了。原因我不怎么想说&#xff0c;玩物丧志了。后面渐渐要恢复之前的写作节奏。今天来聊聊我最近遇到的一个问题&#xff1a; Android 13版本对于storage权限的控制问题。 我们都知道&#xff0c;Andro…...

Android kotlin开源项目-功能标题目录

目录 一、BRVAH二、开源项目1、RV列表动效&#xff08;标题目录&#xff09;2、拖拽与侧滑&#xff08;标题目录&#xff09;3、数据库&#xff08;标题目录&#xff09;4、树形图(多级菜单)&#xff08;标题目录&#xff09;5、轮播图与头条&#xff08;标题目录&#xff09;6…...

Linux下,基于TCP与UDP协议,不同进程下单线程通信服务器

C语言实现Linux下&#xff0c;基于TCP与UDP协议&#xff0c;不同进程下单线程通信服务器 一、TCP单线程通信服务器 先运行server端&#xff0c;再运行client端输入"exit" 是退出 1.1 server_TCP.c **#include <my_head.h>#define PORT 6666 #define IP &qu…...

qt功能自己创作

按钮按下三秒禁用 void MainWindow::on_pushButton_5_clicked(){// 锁定界面setWidgetsEnabled(ui->centralwidget, false);// 创建一个定时器&#xff0c;等待3秒后解锁界面QTimer::singleShot(3000, this, []() {setWidgetsEnabled(ui->centralwidget, true);;//ui-&g…...

Linux网络编程:使用UDP和TCP协议实现网络通信

目录 一. 端口号的概念 二. 对于UDP和TCP协议的认识 三. 网络字节序 3.1 字节序的概念 3.2 网络通信中的字节序 3.3 本地地址格式和网络地址格式 四. socket编程的常用函数 4.1 sockaddr结构体 4.2 socket编程常见函数的功能和使用方法 五. UDP协议实现网络通信 5.…...

【后端速成 Vue】初识指令(上)

前言&#xff1a; Vue 会根据不同的指令&#xff0c;针对标签实现不同的功能。 在 Vue 中&#xff0c;指定就是带有 v- 前缀 的特殊 标签属性&#xff0c;比如&#xff1a; <div v-htmlstr> </div> 这里问题就来了&#xff0c;既然 Vue 会更具不同的指令&#…...

爬虫 — Scrapy-Redis

目录 一、背景1、数据库的发展历史2、NoSQL 和 SQL 数据库的比较 二、Redis1、特性2、作用3、应用场景4、用法5、安装及启动6、Redis 数据库简单使用7、Redis 常用五大数据类型7.1 Redis-String7.2 Redis-List (单值多value)7.3 Redis-Hash7.4 Redis-Set (不重复的)7.5 Redis-Z…...

tcpdump常用命令

需要安装 tcpdump wireshark ifconfig找到网卡名称 eth0, ens192... tcpdump需要root权限 网卡eth0 经过221.231.92.240:80的流量写入到http.cap tcpdump -i eth0 host 221.231.92.240 and port 80 -vvv -w http.cap ssh登录到主机查看排除ssh 22端口的报文 tcpdump -i …...

计算机网络运输层网络层补充

1 CDMA是码分多路复用技术 和CMSA不是一个东西 UPD是只确保发送 但是接收端收到之后(使用检验和校验 除了检验的部分相加 对比检验和是否相等。如果不相同就丢弃。 复用和分用是发生在上层和下层的问题。通过比如时分多路复用 频分多路复用等。TCP IP 应用层的IO多路复用。网…...

java CAS详解(深入源码剖析)

CAS是什么 CAS是compare and swap的缩写&#xff0c;即我们所说的比较交换。该操作的作用就是保证数据一致性、操作原子性。 cas是一种基于锁的操作&#xff0c;而且是乐观锁。在java中锁分为乐观锁和悲观锁。悲观锁是将资源锁住&#xff0c;等之前获得锁的线程释放锁之后&am…...

1786_MTALAB代码生成把通用函数生成独立文件

全部学习汇总&#xff1a; GitHub - GreyZhang/g_matlab: MATLAB once used to be my daily tool. After many years when I go back and read my old learning notes I felt maybe I still need it in the future. So, start this repo to keep some of my old learning notes…...

2023/09/19 qt day3

头文件 #ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include <QDebug> #include <QTime> #include <QTimer> #include <QPushButton> #include <QTextEdit> #include <QLineEdit> #include <QLabel> #include &l…...

Docker 学习总结(78)—— Docker Rootless 让你的容器更安全

前言 在以 root 用户身份运行 Docker 会带来一些潜在的危害和安全风险,这些风险包括: 容器逃逸:如果一个容器以 root 权限运行,并且它包含了漏洞或者被攻击者滥用,那么攻击者可能会成功逃出容器,并在宿主系统上执行恶意操作。这会导致宿主系统的安全性受到威胁。 特权升…...

<6>-MySQL表的增删查改

目录 一&#xff0c;create&#xff08;创建表&#xff09; 二&#xff0c;retrieve&#xff08;查询表&#xff09; 1&#xff0c;select列 2&#xff0c;where条件 三&#xff0c;update&#xff08;更新表&#xff09; 四&#xff0c;delete&#xff08;删除表&#xf…...

java 实现excel文件转pdf | 无水印 | 无限制

文章目录 目录 文章目录 前言 1.项目远程仓库配置 2.pom文件引入相关依赖 3.代码破解 二、Excel转PDF 1.代码实现 2.Aspose.License.xml 授权文件 总结 前言 java处理excel转pdf一直没找到什么好用的免费jar包工具,自己手写的难度,恐怕高级程序员花费一年的事件,也…...

【AI学习】三、AI算法中的向量

在人工智能&#xff08;AI&#xff09;算法中&#xff0c;向量&#xff08;Vector&#xff09;是一种将现实世界中的数据&#xff08;如图像、文本、音频等&#xff09;转化为计算机可处理的数值型特征表示的工具。它是连接人类认知&#xff08;如语义、视觉特征&#xff09;与…...

多种风格导航菜单 HTML 实现(附源码)

下面我将为您展示 6 种不同风格的导航菜单实现&#xff0c;每种都包含完整 HTML、CSS 和 JavaScript 代码。 1. 简约水平导航栏 <!DOCTYPE html> <html lang"zh-CN"> <head><meta charset"UTF-8"><meta name"viewport&qu…...

Rapidio门铃消息FIFO溢出机制

关于RapidIO门铃消息FIFO的溢出机制及其与中断抖动的关系&#xff0c;以下是深入解析&#xff1a; 门铃FIFO溢出的本质 在RapidIO系统中&#xff0c;门铃消息FIFO是硬件控制器内部的缓冲区&#xff0c;用于临时存储接收到的门铃消息&#xff08;Doorbell Message&#xff09;。…...

【JVM面试篇】高频八股汇总——类加载和类加载器

目录 1. 讲一下类加载过程&#xff1f; 2. Java创建对象的过程&#xff1f; 3. 对象的生命周期&#xff1f; 4. 类加载器有哪些&#xff1f; 5. 双亲委派模型的作用&#xff08;好处&#xff09;&#xff1f; 6. 讲一下类的加载和双亲委派原则&#xff1f; 7. 双亲委派模…...

Spring Security 认证流程——补充

一、认证流程概述 Spring Security 的认证流程基于 过滤器链&#xff08;Filter Chain&#xff09;&#xff0c;核心组件包括 UsernamePasswordAuthenticationFilter、AuthenticationManager、UserDetailsService 等。整个流程可分为以下步骤&#xff1a; 用户提交登录请求拦…...

高防服务器价格高原因分析

高防服务器的价格较高&#xff0c;主要是由于其特殊的防御机制、硬件配置、运营维护等多方面的综合成本。以下从技术、资源和服务三个维度详细解析高防服务器昂贵的原因&#xff1a; 一、硬件与技术投入 大带宽需求 DDoS攻击通过占用大量带宽资源瘫痪目标服务器&#xff0c;因此…...

算法—栈系列

一&#xff1a;删除字符串中的所有相邻重复项 class Solution { public:string removeDuplicates(string s) {stack<char> st;for(int i 0; i < s.size(); i){char target s[i];if(!st.empty() && target st.top())st.pop();elsest.push(s[i]);}string ret…...

Axure零基础跟我学:展开与收回

亲爱的小伙伴,如有帮助请订阅专栏!跟着老师每课一练,系统学习Axure交互设计课程! Axure产品经理精品视频课https://edu.csdn.net/course/detail/40420 课程主题:Axure菜单展开与收回 课程视频:...