Java 8 Streams peek Method

Java 8 Stream provides a different approach to process the data. In this article we will look at Java 8 Streams peek method.

Stream Peek Method

Stream interface provides a peek(Consumer<? super T> action) method. This method returns a new stream comprises the elements of the original element. Before we jump in to an example, let’s take a quick look at some important points of the <b>peek()</b> method.

  1. Stream peek() method is an intermediate operation.
  2. It does not operate on the entire collection until terminal operation (More details in the later section)
  3. Returns stream comprises current stream.
  4. It will perform the provided action on each element of the stream.
  5. It’s a like a debugging tool. It allows “performing the provided action on each element as elements are consumed from the resulting stream,”.

1. Java Stream peek() Example

Let’s look at a simple example for better clarity. If we run the following program, you won’t see any output in the console:

List languages = Arrays.asList("Java", "C", "PHP","Scala", "Go");
languages
     .stream()
      .peek(System.out::println); // this will print nothing

output

 No output 

Above code will have no output. Let’s change our code a little to see if we are getting any output:

List < String > languages = Arrays.asList("Java", "C", "PHP", "Scala", "Go");
//languages.stream().peek(System.out::println); // earlier code

List < String > newLangugaes = languages
                                  .stream()
                                  .peek(System.out::println)
                                  .collect(Collectors.toList()); // we use terminal operator

Console Output

Java
C
PHP
Scala
Go

We did not saw any output with the first example because it’s an intermediate operation and we didn’t apply a terminal operation.

There are few important points which we should keep in mind while using the Stream Peek method.

  1. The Java stream peek method mainly to support debugging (e.g. We want to check the element while they are being processed).
  2. One of the main use case for peek method is to find out if the stream element has been processed or not.
  3. Java 9 added few enhancement to the Java stream peek method (performance optimization). If the element size is known and if it remain unchanged in the stream, the peek operation will not be performed (read for more details).
  4. Peek operation dependents upon the terminal operation. the peek operation without terminal operation will do nothing.

2. Intermediate and Terminal Operations

The Java 8 Stream API works in different steps and some of them are required while others are optional. Here is a high level list:

  1. Source – The source data for the stream API.
  2. Intermediate Operations – Optional intermediate operations on the stream.
  3. Terminal Operations – Operations which collect and provide final output.

The distinction between this operation is that an intermediate operation is lazy while a terminal operation is not. When you invoke an intermediate operation on a stream, the operation is not executed immediately. They execute it only when a terminal operation invoked on that stream. If we look at our previous example, We only have output once we use the terminal operator (collect(Collectors.toList())).

3. Peek without terminal Operation

While working on the Java stream peek method, please be aware that it worked with the terminal operation, if we try to use the peek without terminal operation, it does nothing. Let’s see this in action with a simple example

import java.util.Arrays;
import java.util.List;

public class SimpleExample {

    public static void main(String[] args) {

        //creating simple list
        List<String> languages = Arrays.asList("Java", "C", "PHP", "Scala", "Go");

        //use peek without terminal operation
        languages.stream()
                .peek(System.out::println);
    }
}

Output
//nothing as no terminal operator was used

Summary

In this short article, we saw the Java 8 Streams peek method. The <b>Stream.peek()</b> method can be a useful in visualizing how stream operations behave.It can help us to understand the underlying processing of complex stream operations.Be aware not to change the underlying stream using the stream peak method as this is not the true use of the method.The source code for this article is available on our GitHub repository.

Scroll to Top