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
- LongStream peek() in Java with examples
- DoubleStream peek() in Java with examples
- IntStream peek() in Java with examples
- Stream.of(T t) in Java with examples
- Stream map() in Java with examples
- Stream.reduce() in Java with examples
- Stream min() method in Java with Examples
- Stream empty() in Java with Examples
- Stream builder() in Java with Examples
- Stream.max() method in Java with Examples
- Stream toArray() in Java with Examples
- Stream mapToDouble() in Java with examples
- Stream allMatch() in Java with examples
- Stream anyMatch() in Java with examples
- Stream filter() in Java with examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : zemiak