Java:串流中的使用者介面无法正常运作 [英] Java: Consumer interface in a stream doesn't work as expected
问题描述
我有2条语句,我希望它们应该打印"相同的结果:
I've got 2 statements, I expected that they should "print" same result:
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
}
});
实际上,第一个语句将打印
In fact, the first statement will print
a
b
c
好,但是第二条语句不打印任何内容.我试图在IntelliJ中的"//breakpoint"行中设置一个断点,但没有成功.
Ok, but the second statement prints nothing. I tried to set a breakpoint in the line of "//breakpoint" inside IntelliJ, but it wasn't hit.
那么当使用消费者"处理每个元素时,如何在创建新流时更改第二条语句以使用窥视"呢?
So how should I change the second statement to use "peek" as it create a new stream while processing every element using "Consumer"?
非常感谢.
推荐答案
Stream.peek
, as stated in the javadocs of the API as well, is meant mainly for debugging purposes and performing any update operations on the stream during the peek operation is not recommended.
例如,您可以使用以下代码及其最终结果来验证中间流状态:
For example, you can verify the intermediate stream state with the following code and what it eventually results in:
Arrays.stream("acb".split(""))
.peek(System.out::println) // print a c b
.sorted()
.forEach(System.out::println); // print a b c
通常,此操作是中间操作,除非
In general, this operation is an intermediate operation wouldn't be executed unless and terminal operation is performed on the stream as mentioned in the Stream operations and pipelines section of the docs and that is exactly the reason why your first statement will print.
注意 :尽管按照其他一些答案的建议, peek
中的操作如果能够针对 findFirst
等某些短路操作优化结果的情况下,则不会调用此方法.
Note: Though as suggested in a few other answers, the action within peek
is not invoked in the cases when its able to optimize the result for some short-circuiting operations like findFirst
etc.
如果流实现能够优化部分或全部元素的产生(例如,短路诸如
findFirst
之类的操作,或者在count()
)中描述的示例中,这些元素将不会调用该操作.
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 incount()
), the action will not be invoked for those elements.
这篇关于Java:串流中的使用者介面无法正常运作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!