Side Effects in peek: When It's Acceptable
What you'll learn: You'll understand when it's appropriate to use peek for side effects and why modifying external state is generally discouraged.
The Core Principle: Read-Only Debugging
As you've learned, peek exists primarily for debugging — observing stream elements as they flow through the pipeline. The golden rule is that peek should not modify external state or change the elements themselves.
// ✅ Acceptable: Read-only observation for debugging
List<String> names = List.of("Alice", "Bob", "Charlie");
long count = names.stream()
.peek(name -> System.out.println("Processing: " + name))
.filter(n -> n.length() > 4)
.count();
Why Side Effects Are Problematic
Modifying external variables in peek violates the functional nature of streams and can lead to unpredictable behavior, especially with parallel streams:
// ❌ Bad: Modifying external state
List<String> processed = new ArrayList<>();
names.stream()
.peek(processed::add) // DON'T DO THIS
.filter(n -> n.length() > 4)
.collect(Collectors.toList());
This is dangerous because stream laziness and parallel execution can cause elements to be processed in unexpected orders or not at all if short-circuiting occurs.
When Side Effects Might Be Acceptable
The only truly acceptable use of side effects in peek is for temporary debugging purposes — logging, printing, or setting breakpoints. Even then, remember to remove these peek calls in production code:
// Acceptable for debugging sessions
stream.peek(x -> logger.debug("Current value: " + x))
.map(...)
.collect(...);
Key Takeaway: Use peek exclusively for read-only debugging observations, never for modifying external state — if you need side effects, use forEach as a terminal operation or rethink your pipeline design.