我有 2 个语句,我希望它们应该“打印”相同的结果:
Arrays.stream("abc".split("")).forEach(System.out::println);//first
Arrays.stream("abc".split("")).peek(new Consumer<String>() {//second
@Override
public void accept(String s) {
System.out.println(s);//breakpoint
}
});
其实第一条语句会打印
a
b
c
好的,但是第二条语句没有打印任何内容。我尝试在 IntelliJ 中的“//breakpoint”行设置断点,但没有命中。
那么我应该如何更改第二个语句以使用“peek”,因为它在使用“Consumer”处理每个元素时创建一个新流?
非常感谢。
Stream.peek
,如 API 的 javadoc 中所述,主要用于调试目的,不建议在 peek 操作期间对流执行任何更新操作。
例如,您可以使用以下代码验证中间流状态及其最终结果:
Arrays.stream("acb".split(""))
.peek(System.out::println) // print a c b
.sorted()
.forEach(System.out::println); // print a b c
一般来说,这个操作是一个中间操作,除非在Stream operations and pipelines中提到的对流执行终端操作,否则不会执行。文档的一部分,这正是您的第一条语句将被打印的原因。
注意:尽管如其他一些答案中所建议的那样,peek
中的操作
在能够优化某些短路操作(如 findFirst
等)的结果的情况下不会被调用
In cases where the stream implementation is able to optimize away the
production of some or all the elements (such as with short-circuiting
operations like findFirst
, or in the example described in count()
),
the action will not be invoked for those elements.