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

相关文章

java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)

《java中pdf模版填充表单踩坑实战记录(itextPdf、openPdf、pdfbox)》:本文主要介绍java中pdf模版填充表单踩坑的相关资料,OpenPDF、iText、PDFBox是三... 目录准备Pdf模版方法1:itextpdf7填充表单(1)加入依赖(2)代码(3)遇到的问题方法2:pd

Java Stream流之GroupBy的用法及应用场景

《JavaStream流之GroupBy的用法及应用场景》本教程将详细介绍如何在Java中使用Stream流的groupby方法,包括基本用法和一些常见的实际应用场景,感兴趣的朋友一起看看吧... 目录Java Stream流之GroupBy的用法1. 前言2. 基础概念什么是 GroupBy?Stream

python使用try函数详解

《python使用try函数详解》Pythontry语句用于异常处理,支持捕获特定/多种异常、else/final子句确保资源释放,结合with语句自动清理,可自定义异常及嵌套结构,灵活应对错误场景... 目录try 函数的基本语法捕获特定异常捕获多个异常使用 else 子句使用 finally 子句捕获所

SpringBoot监控API请求耗时的6中解决解决方案

《SpringBoot监控API请求耗时的6中解决解决方案》本文介绍SpringBoot中记录API请求耗时的6种方案,包括手动埋点、AOP切面、拦截器、Filter、事件监听、Micrometer+... 目录1. 简介2.实战案例2.1 手动记录2.2 自定义AOP记录2.3 拦截器技术2.4 使用Fi

C++11右值引用与Lambda表达式的使用

《C++11右值引用与Lambda表达式的使用》C++11引入右值引用,实现移动语义提升性能,支持资源转移与完美转发;同时引入Lambda表达式,简化匿名函数定义,通过捕获列表和参数列表灵活处理变量... 目录C++11新特性右值引用和移动语义左值 / 右值常见的左值和右值移动语义移动构造函数移动复制运算符

最新Spring Security的基于内存用户认证方式

《最新SpringSecurity的基于内存用户认证方式》本文讲解SpringSecurity内存认证配置,适用于开发、测试等场景,通过代码创建用户及权限管理,支持密码加密,虽简单但不持久化,生产环... 目录1. 前言2. 因何选择内存认证?3. 基础配置实战❶ 创建Spring Security配置文件

Python对接支付宝支付之使用AliPay实现的详细操作指南

《Python对接支付宝支付之使用AliPay实现的详细操作指南》支付宝没有提供PythonSDK,但是强大的github就有提供python-alipay-sdk,封装里很多复杂操作,使用这个我们就... 目录一、引言二、准备工作2.1 支付宝开放平台入驻与应用创建2.2 密钥生成与配置2.3 安装ali

Spring Security 单点登录与自动登录机制的实现原理

《SpringSecurity单点登录与自动登录机制的实现原理》本文探讨SpringSecurity实现单点登录(SSO)与自动登录机制,涵盖JWT跨系统认证、RememberMe持久化Token... 目录一、核心概念解析1.1 单点登录(SSO)1.2 自动登录(Remember Me)二、代码分析三、

C#中lock关键字的使用小结

《C#中lock关键字的使用小结》在C#中,lock关键字用于确保当一个线程位于给定实例的代码块中时,其他线程无法访问同一实例的该代码块,下面就来介绍一下lock关键字的使用... 目录使用方式工作原理注意事项示例代码为什么不能lock值类型在C#中,lock关键字用于确保当一个线程位于给定实例的代码块中时

MySQL 强制使用特定索引的操作

《MySQL强制使用特定索引的操作》MySQL可通过FORCEINDEX、USEINDEX等语法强制查询使用特定索引,但优化器可能不采纳,需结合EXPLAIN分析执行计划,避免性能下降,注意版本差异... 目录1. 使用FORCE INDEX语法2. 使用USE INDEX语法3. 使用IGNORE IND