Java Stream Peek

Introduction

Let’s say you want to see how elements in the stream are processed in step by step manner.

You may be performing complex stream operations.

Just like you are debugging the code.

Is it possible?

For the same purpose we have something called peek() method which can be invoked.

Peek method

peek() is a non-interfering method which means processed elements should not be modified within the stream.

peek() should be used only for debugging purpose, nothing else.

peek() method takes in Consumer where you can print values at that specific step for debugging purpose.

peek() method is an intermediate operation which returns the stream. Just like for all intermediate operations we must call terminal method to see the results.

Let us take a simple example.

1
2
3
4
5
6
7
IntStream nums = IntStream.range(1, 10);

long count = nums.peek(x -> System.out.println("Value in pipeline: " + x))
        .filter(x -> x % 2 == 0)
        .peek(x -> System.out.println("After filtering: " + x))
        .count();
System.out.println("Total count is : "+count);

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
Value in pipeline: 1
Value in pipeline: 2
After filtering: 2
Value in pipeline: 3
Value in pipeline: 4
After filtering: 4
Value in pipeline: 5
Value in pipeline: 6
After filtering: 6
Value in pipeline: 7
Value in pipeline: 8
After filtering: 8
Value in pipeline: 9
Total count is : 4

In the above example we printing even numbers. In the first peek method we can see all elements are printed since this is the first step.

After that we apply filter method to just take in even numbers.

So in the second peek() method we could see only even numbers processed at that stage.

I hope this clarifies how to use peek() method in Java Streams.