Java Stream peek() Method

The peek() method in Java, part of the java.util.stream.Stream interface, is an intermediate operation that allows you to perform a specified action on each element of the stream as it is consumed. This method is particularly useful for debugging or performing side-effects within the stream pipeline.

Table of Contents

  1. Introduction
  2. peek() Method Syntax
  3. Understanding peek()
  4. Examples
    • Basic Usage
    • Using peek() for Debugging
  5. Real-World Use Case
  6. Conclusion

Introduction

The peek() method allows you to inspect and perform actions on each element of the stream without modifying the elements themselves. This method is commonly used for debugging purposes or for performing side-effects, such as logging or updating statistics.

peek() Method Syntax

The syntax for the peek() method is as follows:

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

Parameters:

  • action: A Consumer that represents the action to be performed on each element of the stream.

Returns:

  • A new Stream with the same elements as the original stream.

Throws:

  • This method does not throw any exceptions.

Understanding peek()

The peek() method processes each element of the stream and applies the specified action to it. The elements themselves are not modified, and the stream retains its original elements. This method is useful for performing operations that have side-effects, such as logging or updating external data structures.

Examples

Basic Usage

To demonstrate the basic usage of peek(), we will create a Stream of strings and use peek() to print each element before performing a terminal operation.

Example

import java.util.stream.Stream;

public class PeekExample {
    public static void main(String[] args) {
        Stream<String> stream = Stream.of("apple", "banana", "cherry");

        // Use peek() to print each element
        stream.peek(System.out::println)
              .forEach(s -> {}); // Terminal operation to trigger the stream processing
    }
}

Output:

apple
banana
cherry

Using peek() for Debugging

This example shows how to use peek() for debugging purposes to inspect the elements of the stream at different stages of the pipeline.

Example

import java.util.stream.Stream;

public class PeekDebuggingExample {
    public static void main(String[] args) {
        Stream<String> stream = Stream.of("apple", "banana", "cherry");

        // Use peek() to print elements at different stages of the pipeline
        stream.peek(e -> System.out.println("Original: " + e))
              .map(String::toUpperCase)
              .peek(e -> System.out.println("Uppercased: " + e))
              .filter(s -> s.startsWith("A"))
              .peek(e -> System.out.println("Filtered: " + e))
              .forEach(s -> {}); // Terminal operation to trigger the stream processing
    }
}

Output:

Original: apple
Uppercased: APPLE
Filtered: APPLE
Original: banana
Uppercased: BANANA
Original: cherry
Uppercased: CHERRY

Real-World Use Case

Logging User Actions

In real-world applications, the peek() method can be used to log user actions while processing a stream of user events.

Example

import java.util.stream.Stream;

public class PeekRealWorldExample {
    static class UserAction {
        String user;
        String action;

        UserAction(String user, String action) {
            this.user = user;
            this.action = action;
        }

        @Override
        public String toString() {
            return user + " performed " + action;
        }
    }

    public static void main(String[] args) {
        Stream<UserAction> actions = Stream.of(
            new UserAction("Alice", "login"),
            new UserAction("Bob", "view page"),
            new UserAction("Charlie", "logout")
        );

        // Use peek() to log each user action
        actions.peek(action -> System.out.println("Logging: " + action))
               .forEach(action -> {}); // Terminal operation to trigger the stream processing
    }
}

Output:

Logging: Alice performed login
Logging: Bob performed view page
Logging: Charlie performed logout

Conclusion

The Stream.peek() method is an intermediate operation that allows you to perform a specified action on each element of the stream as it is consumed. This method is particularly useful for debugging or performing side-effects within the stream pipeline. By understanding and using this method, you can efficiently manage and process streams of values in your Java applications, ensuring that necessary side-effects are performed while processing the elements.

Comments