Java IntStream peek() Method

The peek() method in Java, part of the java.util.stream.IntStream interface, is used to perform an action on each element of the stream as it is consumed. This method is useful for debugging and performing operations without modifying the stream itself.

Table of Contents

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

Introduction

The peek() method returns a stream consisting of the elements of the original stream, additionally performing the provided action on each element as elements are consumed from the resulting stream. This method is an intermediate operation, meaning it returns a new stream and does not modify the original stream.

peek() Method Syntax

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

IntStream peek(IntConsumer action)

Parameters:

  • action: An IntConsumer that represents the action to be performed on each element.

Returns:

  • A new IntStream consisting of the elements of the original stream, with the provided action performed on each element.

Throws:

  • This method does not throw any exceptions.

Understanding peek()

The peek() method allows you to perform a specified action on each element of the stream as it is consumed, without modifying the elements themselves. This is useful for debugging, logging, or performing other side effects.

Examples

Basic Usage

To demonstrate the basic usage of peek(), we will create an IntStream and use peek() to print each element before summing the elements.

Example

import java.util.stream.IntStream;

public class PeekExample {
    public static void main(String[] args) {
        IntStream intStream = IntStream.of(1, 2, 3, 4, 5);

        // Use peek() to print each element and then sum the elements
        int sum = intStream.peek(System.out::println).sum();

        // Print the sum
        System.out.println("Sum: " + sum);
    }
}

Output:

1
2
3
4
5
Sum: 15

Using peek() with Other Stream Operations

This example shows how to use peek() in combination with other stream operations, such as filtering and mapping.

Example

import java.util.stream.IntStream;

public class PeekWithOtherOperationsExample {
    public static void main(String[] args) {
        IntStream intStream = IntStream.range(1, 10);

        // Filter even numbers, use peek() to print them, and map to their squares
        IntStream processedStream = intStream.filter(n -> n % 2 == 0)
                                             .peek(n -> System.out.println("Filtered: " + n))
                                             .map(n -> n * n);

        // Use peek() again to print the squared values and sum them
        int sum = processedStream.peek(n -> System.out.println("Squared: " + n)).sum();

        // Print the sum
        System.out.println("Sum of squares: " + sum);
    }
}

Output:

Filtered: 2
Squared: 4
Filtered: 4
Squared: 16
Filtered: 6
Squared: 36
Filtered: 8
Squared: 64
Sum of squares: 120

Real-World Use Case

Logging Elements During Stream Processing

In real-world applications, the peek() method can be used to log each element during stream processing for debugging or monitoring purposes.

Example

import java.util.stream.IntStream;
import java.util.logging.Logger;

public class LoggingExample {
    private static final Logger logger = Logger.getLogger(LoggingExample.class.getName());

    public static void main(String[] args) {
        IntStream intStream = IntStream.of(10, 20, 30, 40, 50);

        // Use peek() to log each element and then sum the elements
        int sum = intStream.peek(n -> logger.info("Processing number: " + n)).sum();

        // Print the sum
        System.out.println("Sum: " + sum);
    }
}

Output:

Sum: 150

Conclusion

The IntStream.peek() method is used to perform an action on each element of the stream as it is consumed. This method is particularly useful for debugging, logging, and performing other side effects without modifying the stream itself. By understanding and using this method, you can efficiently manage and monitor streams of integer values in your Java applications.

Comments