I tried the following snippet of Java 8 code with peek
.
List list = Arrays.asList(\"Bender\", \"Fry\", \"Leela\");
list.stream().p
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.
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.
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.
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.