Java stream quot;forEachquot; but not consuming stream(Java 流“forEach但不消耗流)
问题描述
有时在处理流的步骤之间对流中的每个元素执行某些操作"(例如打印)会很方便,例如用于调试.
Sometimes it would be handy do "something" (e.g. print) with every element in a stream in between steps of processing the stream, e.g. for debugging.
一个简单的例子可能看起来像这样,不幸的是这不起作用,因为 forEach
消耗流:
A simple example could look like this, unfortunately this does not work as forEach
consumes the stream:
List<String> list = new ArrayList<>();
list.add("one");
list.add("two");
list.add("three");
list.add("four");
List<String> filteredList =
list.stream()
.filter(s -> s.startsWith("t"))
.forEach(System.out::println)
.collect(Collectors.toList());
如何做到这一点?
推荐答案
您正在寻找 peek
操作:
You are looking for the peek
operation:
此方法的存在主要是为了支持调试,您希望在元素流过管道中的某个点时查看它们
This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline
此方法将在 Stream 管道的所有元素被消耗时执行给定的操作.因此,它允许获取 peek 元素.
This method will execute the given action on all elements of the Stream pipeline as they are consumed. As such, it allows to take a peek of the elements.
List<String> filteredList =
list.stream()
.filter(s -> s.startsWith("t"))
.peek(System.out::println)
.collect(Collectors.toList());
这篇关于Java 流“forEach"但不消耗流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 流“forEach"但不消耗流
基础教程推荐
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01