What is peek and Why It Exists
You'll learn what the peek operation does in streams and why it was designed primarily for debugging, not data transformation.
The Core Idea
peek is an intermediate operation that lets you observe each element as it flows through the stream pipeline without modifying it. Think of it as a window into your stream—you can look at what's passing through, perform side effects (like printing or logging), but the elements continue unchanged downstream.
Unlike map, which transforms elements into something new, peek is designed to observe the current state. It takes a Consumer<T> that processes each element but returns void.
Why peek Exists
The primary purpose of peek is debugging. When building complex stream pipelines with multiple filter, map, and other operations, you often want to see what data looks like at different stages. Instead of breaking your pipeline apart, you insert peek to inspect intermediate results:
List<String> names = List.of("Alice", "Bob", "Charlie");
names.stream()
.filter(s -> s.length() > 3)
.peek(s -> System.out.println("After filter: " + s))
.map(String::toUpperCase)
.peek(s -> System.out.println("After map: " + s))
.toList();
Here, peek lets you trace exactly which elements survive the filter and how they're transformed by map.
A Word of Caution
While peek can perform side effects (like adding to an external collection), this violates stream best practices. Streams should be side-effect-free except in terminal operations. Use peek for observation and debugging, not business logic.
Key Takeaway: peek is an intermediate operation designed for debugging stream pipelines by observing elements without transforming them—think of it as inserting print statements into your stream flow.