Stream peek() Method in Java with Examples
In Java, Stream provides an powerful alternative to process data where here we will be discussing one of the very frequently used methods named peek() which being a consumer action basically 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, as 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)
Here, Stream is an interface and T is the type of stream element. 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.Now we need to understand the lifecycle of peek() method via its internal working via clean java programs listed below as follows:
- 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.
From the above output, we can perceive that this piece of code will produce no output
0 2 4 6 8 10