Course contentsShow
← Java
Lesson 1486 of 2,87032. Streams API: Intermediate OperationsFree lesson

peek for Debugging Complex Chains

Strategically placing peek operations between intermediate steps to observe data at each transformation stage.

Using peek to Debug Complex Stream Pipelines

What you'll learn: How to strategically place peek() operations between intermediate steps to observe data at each transformation stage in a multi-step stream pipeline.

When you build complex stream pipelines with multiple map, filter, flatMap, and other intermediate operations chained together, it can be difficult to understand what's happening at each step—especially when results aren't what you expect. This is where peek becomes invaluable.

Strategic Placement for Visibility

The key to debugging with peek is placing it between operations where you want to inspect the data. Think of peek as setting up observation checkpoints along an assembly line—you can watch items pass through each station to verify they're being processed correctly.

List<String> names = Arrays.asList("alice", "bob", "charlie", "david");

List<String> result = names.stream()
    .peek(s -> System.out.println("Original: " + s))
    .filter(s -> s.length() > 3)
    .peek(s -> System.out.println("After filter: " + s))
    .map(String::toUpperCase)
    .peek(s -> System.out.println("After map: " + s))
    .collect(Collectors.toList());

This prints:

Original: alice
After filter: alice
After map: ALICE
Original: bob
Original: charlie
After filter: charlie
After map: CHARLIE
Original: david
After filter: david
After map: DAVID

Notice how you can see exactly which elements survive the filter and how they transform through map. This visibility is crucial when debugging why certain elements disappear or transform unexpectedly.

When to Use This Pattern

Place peek checkpoints:

  • Before and after filter to see what gets removed
  • Between map operations to track transformations
  • After flatMap to verify flattening behavior
  • Before sorted or distinct to see input state

Remember: Remove these debugging peek calls before production—they're tools for development, not permanent fixtures.

Key Takeaway: Strategically placing peek() between intermediate operations creates visibility checkpoints that reveal exactly how data flows and transforms through complex stream pipelines, making debugging straightforward.