I tried the following snippet of Java 8 code with peek
.
List<String> 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?
Description. Stream peek() method is an intermediate operation. It returns a Stream consisting of the elements of current stream. It additionally perform the provided action on each element as elements.
peek() method in Java is used to retrieve or fetch the first element of the Stack or the element present at the top of the Stack. The element retrieved does not get deleted or removed from the Stack. Parameters: The method does not take any parameters.
(1): using stream. foreach, you can also change the internal property value of each item in the list, etc., but you need to perform "secondary flow processing" to get the smallest item in the list (filter according to age). (2): stream. peek can get the smallest item directly compared with stream.
Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With