Stream peek() in Java with examples
Stream peek(Consumer action) 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 i.e, it creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate.
Stream<T> peek(Consumer<? super T> action) Where, Stream is an interface and T is the type of stream elements. action is a non-interfering action to perform on the elements as they are consumed from the stream and the function returns the new stream.
- This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline.
- Since Java 9, if the number of elements is known in advance and unchanged in the stream, the .peek () statement will not be executed due to performance optimization. It is possible to force its operation by a command (formal) changing the number of elements eg. .filter (x -> true).
- Using peek without any terminal operation does nothing.
Example 1 : peek without terminal operation.
Example 2 : peek with terminal operation count.
0 2 4 6 8 10
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.