Printing Elements for Debugging
You'll learn how to use peek with System.out.println to watch data flow through your stream pipeline in real-time.
When building complex stream pipelines, you sometimes need to see what's actually happening at different stages. It's like watching luggage move through an airport security scanner—you want to observe items passing through without stopping the entire process.
Using peek for Print Debugging
The peek operation is perfect for debugging because it lets you "spy" on elements as they flow through the pipeline. The most common debugging use case is simply printing each element:
List<String> names = List.of("Alice", "Bob", "Charlie", "David");
List<String> result = names.stream()
.filter(name -> name.length() > 3)
.peek(System.out::println) // Debug: see what passed the filter
.map(String::toUpperCase)
.collect(Collectors.toList());
// Console output:
// Alice
// Charlie
// David
Inspecting Multiple Pipeline Stages
You can insert multiple peek operations at different points to trace how data transforms:
List<Integer> numbers = List.of(1, 2, 3, 4, 5);
numbers.stream()
.peek(n -> System.out.println("Original: " + n))
.filter(n -> n % 2 == 0)
.peek(n -> System.out.println("After filter: " + n))
.map(n -> n * 10)
.peek(n -> System.out.println("After map: " + n))
.forEach(n -> {}); // Terminal operation needed
This produces a clear trace showing how elements are filtered and transformed at each step.
Key Takeaway: Use peek(System.out::println) or peek(e -> System.out.println("Label: " + e)) to debug stream pipelines by printing elements as they flow through, helping you understand exactly what's happening at each stage without disrupting the pipeline's flow.