Skip to content
Related Articles

Related Articles

Stream peek() in Java with examples
  • Last Updated : 29 Mar, 2019

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.

Syntax :

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.

Note :

  1. This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline.
  2. 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).
  3. Using peek without any terminal operation does nothing.

Example 1 : peek without terminal operation.




// Implementation of Stream.peek()
// in Java 8
import java.util.*;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Creating a list of Integers
        List<Integer> list = Arrays.asList(0, 2, 4, 6, 8, 10);
  
        // Using peek without any terminal
        // operation does nothing. Hence this
        // code will produce no output.
        list.stream().peek(System.out::println);
    }
}

Output :



No Output

Example 2 : peek with terminal operation count.




// Implementation of Stream.peek()
// in Java 8
import java.util.*;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Creating a list of Integers
        List<Integer> list = Arrays.asList(0, 2, 4, 6, 8, 10);
  
        // Using peek with count(), which
        // is a terminal operation
        list.stream().peek(System.out::println).count();
    }
}

Output :

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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :