Java Stream peek() With Examples

In this tutorial we’ll see how to use Java Stream peek() method with the help of few examples.

Syntax of peek() method in Java Stream API

Stream<T> peek(Consumer<? super T> action)

Argument passed to the peek method is of type Consumer functional interface which represents a non-interfering action to perform on the elements as they are consumed from the stream. Method returns a new Stream.

peek() is an intermediate operation which means using peek() without any terminal operation will do nothing.

Java 9 onward, if the number of elements in Stream source is known in advance then no source elements will be traversed and no intermediate operations like peek() will be evaluated. This is a performance optimization.

peek() method exists mainly to support debugging, where you want to see the elements as they flow from one operation to another with in the Stream pipeline.

Java Stream peek() examples

1. In this example peek() method is used to display the stream elements after each operation.

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamPeek {

  public static void main(String[] args) {
     List<String> tempList = Stream.of("one", "two", "three", "four", "five")
         .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());
     
     System.out.println(tempList);
  }
}

Output

Mapped value: THREE
Filtered value: four
Mapped value: FOUR
Filtered value: five
Mapped value: FIVE
[THREE, FOUR, FIVE]

As you can see peek() method is a good way to debug your Stream and see the results of the operation on the Stream.

2. If you don’t have a terminal operation, intermediate operations like peek() are not executed. You can see that by removing the collect() operation from the previous example.

public class StreamPeek {

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

On executing it you won’t get any output.

Related Posts

That’s all for the topic Java Stream peek() With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

Share this post:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.