Java Stream peek() Example

The Java Stream peek() method is an intermediate operation.

The Java Stream peek() method takes a Consumer interface as a parameter. The Consumer will get called for each element in the stream. The peek() method returns a new Stream that contains all the elements in the original stream.


The purpose of the peek() method is, as the method says, to peek at the elements in the stream, not to transform them. Keep in mind that the peek method does not start the internal iteration of the elements in the stream. You need to call a terminal operation for that. 

Java Stream peek() Example 1

Here is a Java Stream peek() example:
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args)
    {
        Stream.of("one", "two", "three", "four")
                .filter(e -> e.length() > 3)
                .peek(e -> System.out.println("Filtered value: " + e))
                .map(String::toUpperCase)
                .peek(e -> System.out.println("Mapped value: " + e))
                .collect(Collectors.toList());
    }
}

Output:

Filtered value: three
Mapped value: THREE
Filtered value: four
Mapped value: FOUR

Java Stream peek() Example 2

Java program to use peek() API to debug the Stream operations and log Stream elements as they are processed.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args)
    {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);

        List<Integer> newList = list.stream()
                .peek(System.out::println)
                .collect(Collectors.toList());

        System.out.println(newList);
    }
}

Output:

1
2
3
4
5
[1, 2, 3, 4, 5]
As peek()‘s Javadoc page says: “This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline“.