Java8 Stream的各种使用姿势

2024-06-23 12:48
文章标签 java 使用 stream 姿势

本文主要是介绍Java8 Stream的各种使用姿势,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Stream简介

  Java 8 API添加了一个新的抽象称为流(Stream),它可以让你以一种声明的方式处理数据。这种风格将要处理的元素集合看作一种流,流在管道中传输,并且可以在管道的节点上进行处理,比如筛选,排序,聚合等。

概括来说:Stream的出生就是为了代码好看、为了性能高

如何Debug

  在IDEADebug窗口找到Trace Current Stream Chain按钮,点击打开就行啦。

Stream常用到的方法

List<TestRes> list = Arrays.asList(new TestRes().setId(1L).setSiteId(1L),new TestRes().setId(2L).setSiteId(1L),new TestRes().setId(3L).setSiteId(2L),new TestRes().setId(4L).setSiteId(2L),new TestRes().setId(5L).setSiteId(2L),new TestRes().setId(6L).setSiteId(2L)
);// 1. map(), 维度不变, 一一映射
// List<Long> idList = list.stream().map(e -> {
//     return e.getId();
// }).collect(Collectors.toList());
List<Long> idList = list.stream().map(TestRes::getId).collect(Collectors.toList());// 2. reduce(), 降维处理, 允许默认值
Integer result = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9}
).reduce(0, Integer::sum);// 3. filter(), 过滤器
// List<TestRes> resList = list.stream().filter(e -> {
//     return e.getId() >= 3L;
// }).collect(Collectors.toList());
List<TestRes> resList = list.stream().filter(e -> e.getId() >= 3L
).collect(Collectors.toList());// 4. limit(), 限制流数量
List<TestRes> limitResList = list.stream().limit(3).collect(Collectors.toList());// 5. count(), 计数
long count = list.stream().filter(Objects::nonNull).count();// 6. sort(), 排序, 可自定义比较器
List<Integer> sortList = Arrays.stream(new Integer[]{9, 8, 7, 6, 5, 4, 3, 2, 1}
).sorted().collect(Collectors.toList());

根据Map的Value排序

Map<Long, TestRes> map = new HashMap<>();
map.put(1L, new TestRes().setId(1L).setHits(3));
map.put(2L, new TestRes().setId(2L).setHits(5));
map.put(3L, new TestRes().setId(3L).setHits(2));
map.put(4L, new TestRes().setId(4L).setHits(4));
map.put(5L, new TestRes().setId(5L).setHits(1));List<TestRes> sortResult = new ArrayList<>();
map.entrySet().stream().sorted(Comparator.comparingInt(o -> o.getValue().getHits())
).forEachOrdered(entry -> {sortResult.add(entry.getValue());
});

其他操作:
.distinct() 去重;
.flatMap() 流的扁平化操作;
.forEach() 遍历, void式操作; .peek() 遍历, 返回新的流;
.findFirst() 查找第一个满足条件的元素; .findAny() 查找任一满足条件的元素
.anyMatch() 有无匹配元素; .allMatch() 是否全部匹配; .noneMatch() 是否无一匹配;
.max() 找最大值, 可自定义比较器; .min() 找最小值, 可自定义比较器;

Stream常用到的收集器

// 1. toList()
// 2. groupingBy()
Map<Long, List<TestRes>> listMap = list.stream().collect(Collectors.groupingBy(TestRes::getSiteId, Collectors.toList())
);// 3. toMap()
Map<Long, TestRes> resMap = list.stream().collect(Collectors.toMap(TestRes::getId, Function.identity())
);// 4. toSet()
Set<String> set = Arrays.stream(new String[]{"Java", "Python", "C", "Java"}
).collect(Collectors.toSet());// 5. joining()
String join = list.stream().map(e -> e.getId().toString()
).collect(Collectors.joining(","));

Stream使用时性能隐患注意点

处理N+1查询

/*************************************************************************
* 【需求:查询所有站点下的全部资源,并打印所有资源及其所属站点】
*************************************************************************/
List<Site> sites = siteService.selectByExample(Example.builder(Site.class).andWhere(Sqls.custom().andIn("id", Arrays.asList(58L, 49L, 76L, 91L, 81L))).build()
);/******************************** old  ********************************/
long to1 = Instant.now().toEpochMilli();
sites.forEach(site -> {List<TestRes> resList = resService.select(new TestRes().setSiteId(site.getId()));resList.forEach(res -> {// System.out.println(//     String.format("%s, res from ==> %s", res.getName(), site.getName())// );});
});
log.info("old method complete in ==> {}", Instant.now().toEpochMilli() - to1);
// old method complete in ==> 627/******************************** new  ********************************/
long tn1 = Instant.now().toEpochMilli();
// 批量查询所有资源
List<Long> siteIds = fors.stream().map(Site::getId).collect(Collectors.toList());
List<TestRes> resList = resService.selectByExample(Example.builder(TestRes.class).andWhere(Sqls.custom().andIn("siteId", siteIds)).build()
);// 构造站点映射集
Map<Long, Site> siteMap = sites.stream().collect(Collectors.toMap(Site::getId, Function.identity())
);// 根据站点映射集查找词条所属站点
resList.forEach(res -> {Site site = siteMap.getOrDefault(res.getSiteId(), new Site().setName("-"));// System.out.println(//     String.format("%s, page from ==> %s", res.getName(), site.getName())// );
});
log.info("new method complete in ==> {}", Instant.now().toEpochMilli() - tn1);
// new method complete in ==> 86

结果显示,老方法耗时627ms, 使用IN查询+映射集只需要86ms

树形结构建立

/*************************************************************************
* 【需求:将某篇资源的所有评论整理成树形结构(root 10个元素,2层树形)】
*************************************************************************/
/******************************** old  ********************************/
long to2 = Instant.now().toEpochMilli();
// 查询一级评论
List<Comment> parentComments = commentService.selectByExample(Example.builder(Comment.class).andWhere(Sqls.custom().andEqualTo("sourceId", 1L).andIsNull("childOfId")).orderByDesc("createdAt").build()
);// 遍历一级评论构造子评论列表
List<List<Comment>> resultOld = parentComments.stream().map(parentComment -> {List<Comment> childs = commentService.select(new Comment().setSourceId(parentComment.getSourceId()).setChildOfId(parentComment.getId()));// do somethingreturn childs;
}).collect(Collectors.toList());
log.info("old tree build in ==> {}", Instant.now().toEpochMilli() - to2);
// old tree build in ==> 1219/******************************** new  ********************************/
long tn2 = Instant.now().toEpochMilli();
// 查询所有评论
List<Comment> comments = commentService.selectByExample(Example.builder(Comment.class).andWhere(Sqls.custom().andEqualTo("sourceId", 1L)).orderByDesc("createdAt").build()
);// 根据评论父ID分组
Map<Long, List<Comment>> commentsMap = comments.stream().filter(e -> null != e.getChildOfId()
).collect(Collectors.groupingBy(Comment::getChildOfId, Collectors.toList())
);// 筛选一级评论
List<Comment> rootComments = comments.stream().filter(e -> null == e.getChildOfId()
).collect(Collectors.toList());// 遍历一级评论,查找映射集中的子评论列表
List<List<Comment>> resultNew = rootComments.stream().map(e -> {List<Comment> childs = commentsMap.getOrDefault(e.getId(), Collections.emptyList());// do somethingreturn childs;
}).collect(Collectors.toList());
log.info("new tree build in ==> {}", Instant.now().toEpochMilli() - tn2);
// new tree build in ==> 98

结果显示,老方法耗时1219ms, 使用新方法构造树只需要98ms

结论

  尽量避免在stream中间函数做数据库查询,若情况合适,利用流式特性直接在内存进行筛选分组等操作,以此优化性能。

这篇关于Java8 Stream的各种使用姿势的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1087202

相关文章

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

Windows下C++使用SQLitede的操作过程

《Windows下C++使用SQLitede的操作过程》本文介绍了Windows下C++使用SQLite的安装配置、CppSQLite库封装优势、核心功能(如数据库连接、事务管理)、跨平台支持及性能优... 目录Windows下C++使用SQLite1、安装2、代码示例CppSQLite:C++轻松操作SQ

SpringBoot整合Flowable实现工作流的详细流程

《SpringBoot整合Flowable实现工作流的详细流程》Flowable是一个使用Java编写的轻量级业务流程引擎,Flowable流程引擎可用于部署BPMN2.0流程定义,创建这些流程定义的... 目录1、流程引擎介绍2、创建项目3、画流程图4、开发接口4.1 Java 类梳理4.2 查看流程图4

一文详解如何在idea中快速搭建一个Spring Boot项目

《一文详解如何在idea中快速搭建一个SpringBoot项目》IntelliJIDEA作为Java开发者的‌首选IDE‌,深度集成SpringBoot支持,可一键生成项目骨架、智能配置依赖,这篇文... 目录前言1、创建项目名称2、勾选需要的依赖3、在setting中检查maven4、编写数据源5、开启热

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

Java对异常的认识与异常的处理小结

《Java对异常的认识与异常的处理小结》Java程序在运行时可能出现的错误或非正常情况称为异常,下面给大家介绍Java对异常的认识与异常的处理,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参... 目录一、认识异常与异常类型。二、异常的处理三、总结 一、认识异常与异常类型。(1)简单定义-什么是

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

Python中help()和dir()函数的使用

《Python中help()和dir()函数的使用》我们经常需要查看某个对象(如模块、类、函数等)的属性和方法,Python提供了两个内置函数help()和dir(),它们可以帮助我们快速了解代... 目录1. 引言2. help() 函数2.1 作用2.2 使用方法2.3 示例(1) 查看内置函数的帮助(

Linux脚本(shell)的使用方式

《Linux脚本(shell)的使用方式》:本文主要介绍Linux脚本(shell)的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录概述语法详解数学运算表达式Shell变量变量分类环境变量Shell内部变量自定义变量:定义、赋值自定义变量:引用、修改、删

SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志

《SpringBoot项目配置logback-spring.xml屏蔽特定路径的日志》在SpringBoot项目中,使用logback-spring.xml配置屏蔽特定路径的日志有两种常用方式,文中的... 目录方案一:基础配置(直接关闭目标路径日志)方案二:结合 Spring Profile 按环境屏蔽关