What is the peek method in Java Stream API and how to use it?

The peek method in Java’s Stream API is an intermediary operation. This method provides a way to inspect the elements in the stream as they’re being processed by other stream operations. However, it’s important to note that peek should only be used for debugging purposes, as it can be quite disruptive to the stream’s data flow, particularly when it’s used in parallel streams.

The key point of the peek operation is that it’s not a terminal operation (i.e., it doesn’t trigger data processing), instead, it integrates nicely within the operation chain, allowing insights to be gained during the processing phase.

Here’s a simple way of using it with Java:

package org.kodejava.util;

import java.util.stream.Stream;

public class PeekMethodStream {
    public static void main(String[] args) {
        Stream.of(1, 2, 3, 4, 5)
                .peek(i -> System.out.println("Number: " + i))
                .map(i -> i * i)
                .forEach(i -> System.out.println("Squared: " + i));
    }
}

Output:

Number: 1
Squared: 1
Number: 2
Squared: 4
Number: 3
Squared: 9
Number: 4
Squared: 16
Number: 5
Squared: 25

In this code snippet:

  • We create a stream with Stream.of(1, 2, 3, 4, 5).
  • Then we use peek to print each element in its current state: “Number: 1”, “Number: 2”, etc.
  • After that, we use map to square each element.
  • Finally, we use forEach to print the squared numbers: “Squared: 1”, “Squared: 4”, etc.

Remember, use peek carefully and preferably only for debugging purposes.

Wayan

Leave a Reply

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