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 and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
- IntStream peek() in Java with examples
- DoubleStream peek() in Java with examples
- LongStream peek() in Java with examples
- DelayQueue peek() method in Java with Examples
- BlockingDeque peek() method in Java with examples
- Java.util.LinkedList.peek() , peekfirst(), peeklast() in Java
- ArrayBlockingQueue peek() Method in Java
- PriorityQueue peek() Method in Java
- ArrayDeque peek() Method in Java
- Stack peek() Method in Java
- LinkedBlockingQueue peek() method in Java
- PriorityBlockingQueue peek() method in Java
- LinkedBlockingDeque peek() method in Java
- LinkedTransferQueue peek() method in Java
- ConcurrentLinkedQueue peek() method in Java
- Queue peek() method in Java
- ConcurrentLinkedDeque peek() method in Java with Example
- Character Stream Vs Byte Stream in Java
- Difference between Stream.of() and Arrays.stream() method in Java
- foreach() loop vs Stream foreach() vs Parallel Stream foreach()
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