当前位置: 首页 > 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 权限运行,并且它包含了漏洞或者被攻击者滥用,那么攻击者可能会成功逃出容器,并在宿主系统上执行恶意操作。这会导致宿主系统的安全性受到威胁。 特权升…...

国防科技大学计算机基础课程笔记02信息编码

1.机内码和国标码 国标码就是我们非常熟悉的这个GB2312,但是因为都是16进制&#xff0c;因此这个了16进制的数据既可以翻译成为这个机器码&#xff0c;也可以翻译成为这个国标码&#xff0c;所以这个时候很容易会出现这个歧义的情况&#xff1b; 因此&#xff0c;我们的这个国…...

模型参数、模型存储精度、参数与显存

模型参数量衡量单位 M&#xff1a;百万&#xff08;Million&#xff09; B&#xff1a;十亿&#xff08;Billion&#xff09; 1 B 1000 M 1B 1000M 1B1000M 参数存储精度 模型参数是固定的&#xff0c;但是一个参数所表示多少字节不一定&#xff0c;需要看这个参数以什么…...

阿里云ACP云计算备考笔记 (5)——弹性伸缩

目录 第一章 概述 第二章 弹性伸缩简介 1、弹性伸缩 2、垂直伸缩 3、优势 4、应用场景 ① 无规律的业务量波动 ② 有规律的业务量波动 ③ 无明显业务量波动 ④ 混合型业务 ⑤ 消息通知 ⑥ 生命周期挂钩 ⑦ 自定义方式 ⑧ 滚的升级 5、使用限制 第三章 主要定义 …...

Cesium1.95中高性能加载1500个点

一、基本方式&#xff1a; 图标使用.png比.svg性能要好 <template><div id"cesiumContainer"></div><div class"toolbar"><button id"resetButton">重新生成点</button><span id"countDisplay&qu…...

JVM暂停(Stop-The-World,STW)的原因分类及对应排查方案

JVM暂停(Stop-The-World,STW)的完整原因分类及对应排查方案,结合JVM运行机制和常见故障场景整理而成: 一、GC相关暂停​​ 1. ​​安全点(Safepoint)阻塞​​ ​​现象​​:JVM暂停但无GC日志,日志显示No GCs detected。​​原因​​:JVM等待所有线程进入安全点(如…...

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

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

Docker 本地安装 mysql 数据库

Docker: Accelerated Container Application Development 下载对应操作系统版本的 docker &#xff1b;并安装。 基础操作不再赘述。 打开 macOS 终端&#xff0c;开始 docker 安装mysql之旅 第一步 docker search mysql 》〉docker search mysql NAME DE…...

Git 3天2K星标:Datawhale 的 Happy-LLM 项目介绍(附教程)

引言 在人工智能飞速发展的今天&#xff0c;大语言模型&#xff08;Large Language Models, LLMs&#xff09;已成为技术领域的焦点。从智能写作到代码生成&#xff0c;LLM 的应用场景不断扩展&#xff0c;深刻改变了我们的工作和生活方式。然而&#xff0c;理解这些模型的内部…...

Caliper 配置文件解析:fisco-bcos.json

config.yaml 文件 config.yaml 是 Caliper 的主配置文件,通常包含以下内容: test:name: fisco-bcos-test # 测试名称description: Performance test of FISCO-BCOS # 测试描述workers:type: local # 工作进程类型number: 5 # 工作进程数量monitor:type: - docker- pro…...

tomcat指定使用的jdk版本

说明 有时候需要对tomcat配置指定的jdk版本号&#xff0c;此时&#xff0c;我们可以通过以下方式进行配置 设置方式 找到tomcat的bin目录中的setclasspath.bat。如果是linux系统则是setclasspath.sh set JAVA_HOMEC:\Program Files\Java\jdk8 set JRE_HOMEC:\Program Files…...