可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.