Java Stream peek() Example

1. Introduction

The peek() method in Java Streams is an intermediate operation that allows you to perform a specified action on each element of the stream as they are consumed from the operations pipeline. Often used for debugging purposes, peek() can help developers see inside the stream without altering the flow of data. It's particularly useful for logging the current state of elements at a specific point in the stream.

Key Points

1. peek() is used to view each element without disrupting the pipeline of stream operations.

2. It enables action on each element as they pass through, often used for debugging or logging.

3. Being an intermediate operation, it does not execute until a terminal operation is invoked on the stream.

2. Program Steps

1. Import necessary classes.

2. Create a stream of elements.

3. Use peek() to perform an action on each element.

4. Apply a terminal operation to trigger the execution of peek().

5. Print the final results.

3. Code Program

import java.util.stream.Stream;

public class StreamPeekExample {

    public static void main(String[] args) {
        // Step 2: Create a stream of elements
        Integer[] numbers = {1, 2, 3, 4, 5};

        // Step 3 and 4: Use peek() to log each element and collect to list
        Integer[] processedNumbers = Stream.of(numbers)
                                           .peek(num -> System.out.println("Processing number: " + num))
                                           .toArray(Integer[]::new);

        // Step 5: Output the processed numbers (not necessarily needed as peek has its output)
        System.out.println("Processed numbers:");
        Stream.of(processedNumbers).forEach(System.out::println);
    }
}

Output:

Processing number: 1
Processing number: 2
Processing number: 3
Processing number: 4
Processing number: 5
Processed numbers:
1
2
3
4
5

Explanation:

1. Stream Creation: The program starts by creating an array of integers and converting it into a Stream using Stream.of().

2. Using peek(): The peek() method is invoked with a lambda expression that prints a message for each element. This is useful for tracking what elements are being processed as the stream operations are applied.

3. Terminal Operation: The toArray() method acts as a terminal operation that triggers the execution of the stream pipeline, including the peek() operation. Without this terminal operation, peek() would not execute because intermediate operations in streams are lazy.

4. Result Output: The elements processed through peek() are then printed again, this time after the peek() operation, demonstrating that the elements remain unchanged. This confirms that peek() is purely for viewing or debugging purposes and does not modify the stream.

5. Utility and Use Case: This example illustrates how peek() can be effectively used for debugging or monitoring the state of each element during stream processing. It's particularly useful in complex streams where understanding the transformations or operations at each step is crucial.


Comments