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.

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);
    }
}

chevron_right


Output :

No Output

Example 2 : peek with terminal operation count.

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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();
    }
}

chevron_right


Output :

0
2
4
6
8
10


My Personal Notes arrow_drop_up

In love with a semicolon because sometimes i miss it so badly)

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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