Java 8 Streams peek api

匿名 (未验证) 提交于 2019-12-03 01:22:02

问题:

I tried the following snippet of Java 8 code with peek.

List list = Arrays.asList("Bender", "Fry", "Leela"); list.stream().peek(System.out::println); 

However there is nothing printed out on the console. If I do this instead:

list.stream().peek(System.out::println).forEach(System.out::println); 

I see the following which outputs both the peek as well as foreach invocation.

Bender Bender Fry Fry Leela Leela 

Both foreach and peek take in a (Consumer super T> action) So why is the output different?

回答1:

The Javadoc mentions the following:

Intermediate operations return a new stream. They are always lazy; executing an intermediate operation such as filter() does not actually perform any filtering, but instead creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate. Traversal of the pipeline source does not begin until the terminal operation of the pipeline is executed.

peek being an intermediate operation does nothing. On applying a terminal operation like foreach, the results do get printed out as seen.



回答2:

The documentation for peek says

Returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream. This is an intermediate operation.

You therefore have to do something with the resulting stream for System.out.println to do anything.



回答3:

From the docs on Stream for the peek method:

...additionally performing the provided action on each element as elements are consumed from the resulting stream.



回答4:

Streams in Java-8 are lazy, in addition, say if there are two chained operations in stream one after the other, then the second operation begins as soon as first one finishes processing a unit of data element (given there is a terminal operation in the stream).

This is the reason why you can see repeated name strings getting output.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!