java - 为什么 flatMap 后采集会改变 Stream 处理顺序?
问题描述
当我运行以下代码时:
Stream.of("a", "b", "c")
.flatMap(s -> Stream.of(s, s+s))
.map(s -> {System.out.printf("complex operation on %s\n", s); return s;})
.findFirst()
.ifPresent(s -> System.out.printf("outcome %s\n", s));
...该map
操作针对流中的前两个元素运行,而不仅仅是第一个:
complex operation on a
complex operation on aa
outcome a
但是,如果我明确地collect
在flatMap
:
Stream.of("a", "b", "c")
.flatMap(s -> Stream.of(s, s + s))
.collect(Collectors.toList())
.stream()
.map(s -> {System.out.printf("complex operation on %s\n", s); return s;})
.findFirst()
.ifPresent(s -> System.out.printf("outcome %s\n", s));
...然后map
操作仅在第一个元素上运行,正如我所期望的那样。
为什么有区别,我怎样才能让map
只处理第一个项目而不收集整个传入流?
请注意,这不是我的实际代码。在实践中,我需要filter
在 the 之后map
和之前findFirst
,所以我不能做类似 call findFirst
before的事情map
。
我也试过:
.sequential()
之后flatMap
(没有效果).sorted()
之后flatMap
(有效,但读取整个流,在我的实际应用程序中,排序实际上没有意义)
解决方案
看起来根本原因的答案也在这里:为什么在 flatMap() 之后的 filter() 在 Java 流中“不完全”是惰性的?
显然,这是一个将在 Java 10 中修复的已知错误。请参阅JDK-8075939。
推荐阅读
- ubuntu - tftp options put 选项不上传文件
- node.js - Mikro ORM:属性在 orm.em.create() 上有任何类型;
- rust - 为什么在 rust 中写入文件时出现“错误的文件描述符”错误?
- c++ - 如何在 Visual Studio 项目中使用 C++ 库方法
- hex - 假设您购买具有 512 MB RAM 的 32 位 PC。已安装内存的最后一个字节的 8 位十六进制数字地址是什么?
- python - 如何检测图像中的凸/凹曲线?
- c++ - 深色主题不适用于标题栏
- python - Selenium 找不到 xpath 或 css 选择器
- mysql - mysql: Media Wiki Extension 问题(空白页)
- javascript - 使用 BroadcastChannel API 反应获取错误