Java LongStream peek() Method

The peek() method in Java, part of the java.util.stream.LongStream interface, is used to perform an action for each element of the stream as elements are consumed from the resulting stream. This method is useful for debugging and performing side-effects during the processing of the stream.

Table of Contents

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

Introduction

The peek() method allows you to perform an action on each element of the stream as it is processed. This is particularly useful for debugging purposes or when you need to perform some side-effect operation, such as logging or updating an external data structure.

peek() Method Syntax

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

LongStream peek(LongConsumer action)

Parameters:

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

Returns:

  • A new LongStream with the same elements as the original stream, where the specified action is performed on each element as it is consumed.

Throws:

  • This method does not throw any exceptions.

Understanding peek()

The peek() method processes each element of the stream and performs the specified action on it without modifying the elements themselves. This method is intermediate, meaning it returns a new stream and does not terminate the stream pipeline. It is primarily used for side-effects such as logging, debugging, or updating external states.

Examples

Basic Usage

To demonstrate the basic usage of peek(), we will create a LongStream and use peek() to print each element as it is processed.

Example

import java.util.stream.LongStream;

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

        // Use peek() to print each element as it is processed
        stream.peek(System.out::println)
              .forEach(n -> {});  // Consuming the stream to trigger peek
    }
}

Output:

1
2
3
4
5

Using peek() with Filtering and Mapping

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

Example

import java.util.stream.LongStream;

public class PeekWithFilterAndMapExample {
    public static void main(String[] args) {
        LongStream stream = LongStream.of(10L, 20L, 30L, 40L, 50L);

        // Use peek() to log elements before and after filtering and mapping
        LongStream resultStream = stream
            .peek(n -> System.out.println("Before filter: " + n))
            .filter(n -> n > 20)
            .peek(n -> System.out.println("After filter: " + n))
            .map(n -> n / 10)
            .peek(n -> System.out.println("After map: " + n));

        // Consume the stream to trigger peek
        resultStream.forEach(n -> {});
    }
}

Output:

Before filter: 10
Before filter: 20
Before filter: 30
After filter: 30
After map: 3
Before filter: 40
After filter: 40
After map: 4
Before filter: 50
After filter: 50
After map: 5

Real-World Use Case

Logging Transaction Amounts

In real-world applications, the peek() method can be used to log transaction amounts at different stages of processing, such as before and after applying a discount.

Example

import java.util.stream.LongStream;

public class PeekTransactionExample {
    public static void main(String[] args) {
        LongStream transactionAmounts = LongStream.of(1000L, 2000L, 1500L, 3000L, 2500L);

        double discountRate = 0.1;

        // Use peek() to log transaction amounts before and after applying a discount
        LongStream discountedTransactions = transactionAmounts
            .peek(amount -> System.out.println("Original amount: " + amount))
            .map(amount -> (long)(amount * (1 - discountRate)))
            .peek(amount -> System.out.println("Discounted amount: " + amount));

        // Consume the stream to trigger peek
        discountedTransactions.forEach(amount -> {});
    }
}

Output:

Original amount: 1000
Discounted amount: 900
Original amount: 2000
Discounted amount: 1800
Original amount: 1500
Discounted amount: 1350
Original amount: 3000
Discounted amount: 2700
Original amount: 2500
Discounted amount: 2250

Conclusion

The LongStream.peek() method is used to perform an action for each element of the stream as it is consumed. This method is particularly useful for debugging and performing side-effects, such as logging or updating external data structures. By understanding and using this method, you can efficiently manage and monitor streams of values in your Java applications, ensuring that side-effects are correctly applied as needed.

Comments