Java Stream peek() Method Example
In this blog, we’ll explore the Java 8 Stream peek()
method, understanding its purpose and demonstrating how it can be effectively used with examples.
Understanding peek()
The peek()
method is an intermediate operation in the Java Stream API. Its primary purpose is to provide a way to execute a specified action on each element of the stream without affecting the stream’s elements or order. It allows developers to perform side effects, such as logging or debugging, while processing the elements in the stream.
The method signature of peek()
is as follows:
Stream<T> peek(Consumer<? super T> action);
Here, action
is a functional interface representing the operation to be performed on each element of the stream.
Example 1: Logging Elements
Let’s say you have a list of numbers and you want to log each element while processing the stream:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.stream()
.peek(n -> System.out.println("Processing element: " + n))
.map(n -> n * 2)
.forEach(System.out::println);
In this example, the peek()
method is used to log each element before doubling its value. The output will include the log statements as well as the final processed elements.
Example 2: Debugging with peek()
Consider a scenario where you have a stream of strings, and you want to debug by printing the length of each string:
List<String> words = Arrays.asList("apple", "banana", "orange", "grape");
words.stream()
.peek(s -> System.out.println("Length of '" + s + "': " + s.length()))
.filter(s -> s.length() > 5)
.forEach(System.out::println);
Here, the peek()
method is used to inspect the length of each string in the stream. It helps in understanding the flow of data and identifying any issues during processing.
Example 3: Conditional Logging
Suppose you have a stream of transactions, and you want to log only the successful ones:
List<Transaction> transactions = // initialize your list of transactions
transactions.stream()
.peek(t -> {
if (t.isSuccessful()) {
System.out.println("Successful transaction: " + t);
}
})
.mapToDouble(Transaction::getAmount)
.sum();
In this example, peek()
is used to conditionally log only successful transactions. This can be valuable for tracking specific events in the stream.
Important Considerations
While peek()
is a handy tool for debugging and logging during stream processing, it’s crucial to use it judiciously. Excessive use of peek()
for side effects may lead to code that is difficult to understand and maintain. It is recommended to primarily focus on using peek()
for debugging purposes.
Summary
In conclusion, the peek()
method in Java Streams provides a convenient way to perform non-destructive, side-effect-producing operations on stream elements. By incorporating it strategically into your stream pipelines, you can gain valuable insights into the data processing flow and simplify debugging tasks.
References
- Java 8 Stream.peek
- Java 8 Stream filter() Method Example
- forEach() vs. forEachOrdered() in Java Stream