Common peek Pitfalls: Lazy Evaluation
You'll learn why peek sometimes appears to "do nothing" and how lazy evaluation catches developers off guard.
The Confusing Silence of peek
The most common pitfall with peek is forgetting that it's an intermediate operation—which means it won't execute at all without a terminal operation. Developers coming from imperative programming often write code like this:
Stream.of("apple", "banana", "cherry")
.peek(fruit -> System.out.println("Processing: " + fruit));
// Nothing prints!
This code compiles fine but prints absolutely nothing. Why? There's no terminal operation triggering the stream pipeline. The peek operation is defined but never executed—like writing instructions on paper but never following them.
The Fix: Add a Terminal Operation
Stream.of("apple", "banana", "cherry")
.peek(fruit -> System.out.println("Processing: " + fruit))
.count(); // Terminal operation triggers execution
// Now it prints!
Why This Trips People Up
Think of a stream pipeline like a lazy factory assembly line. The peek operation is like installing a quality inspection station, but if you never start the assembly line (with a terminal operation like count, collect, or forEach), no products move through, so no inspections happen.
Developers expect peek to behave eagerly—like forEach would on a collection—but streams only execute when explicitly told to produce a result.
Watch for Empty Pipelines
This pitfall is especially sneaky during debugging. You add peek to see what's happening, but if you forget the terminal operation, you see nothing and might wrongly conclude your stream source is empty.
Key Takeaway: peek does nothing without a terminal operation. Always remember that intermediate operations like peek are lazy—they only execute when the stream is consumed by a terminal operation.