Observing Transformations Between Operations
What you'll learn: How to use multiple peek calls strategically placed throughout a stream pipeline to trace how your data transforms at each step.
Why Multiple peek Calls?
Think of peek as placing security cameras at different points in a factory assembly line. Each camera shows you what the product looks like at that moment. By installing cameras between different workstations, you can see exactly how each station transforms the product.
Similarly, you can insert peek operations between map, filter, distinct, sorted, and other intermediate operations to watch your data evolve through the pipeline.
Seeing Data Flow in Action
List<String> words = List.of("apple", "Banana", "cherry", "APPLE", "banana");
List<String> result = words.stream()
.peek(s -> System.out.println("Original: " + s))
.map(String::toLowerCase)
.peek(s -> System.out.println("After map: " + s))
.filter(s -> s.startsWith("a"))
.peek(s -> System.out.println("After filter: " + s))
.distinct()
.peek(s -> System.out.println("After distinct: " + s))
.collect(Collectors.toList());
Output shows each stage:
Original: apple
After map: apple
After filter: apple
After distinct: apple
Original: Banana
After map: banana
Original: cherry
After map: cherry
Original: APPLE
After map: apple
After filter: apple
Original: banana
After map: banana
After filter: banana
Notice how each element flows through the pipeline individually, and you can see exactly when elements get filtered out or deduplicated.
When This Is Invaluable
This technique is essential when debugging complex pipelines where unexpected results occur. Instead of guessing which operation caused the problem, you see the data at each transformation point.
Key Takeaway: Place peek calls between intermediate operations to create checkpoints that reveal how data transforms through your pipeline, making debugging and understanding stream behavior much easier.