peek vs forEach: Key Differences
You'll learn: Why peek() is intermediate while forEach() is terminal, and when each operation is appropriate.
The Fundamental Distinction
Although both peek() and forEach() accept a Consumer<T> and perform an action on each element, they serve entirely different purposes in stream pipelines:
peek()is intermediate – it returns a new stream and doesn't trigger executionforEach()is terminal – it consumes the stream and triggers the entire pipeline
Think of peek() as a window you install along a water pipe to observe flow, while forEach() is the final drain that actually makes the water flow through the entire system.
When to Use Each
Use peek() when:
- Debugging multi-step pipelines (observing elements between operations)
- Performing side effects while continuing the pipeline
- You need more operations after the action
Stream.of(1, 2, 3, 4)
.filter(n -> n > 2)
.peek(n -> System.out.println("After filter: " + n))
.map(n -> n * 2)
.peek(n -> System.out.println("After map: " + n))
.collect(Collectors.toList()); // Terminal operation needed
Use forEach() when:
- Performing final actions on elements (printing results, saving to database)
- You're done with the stream and need no further operations
- You want to ensure the pipeline executes immediately
Stream.of(1, 2, 3, 4)
.filter(n -> n > 2)
.map(n -> n * 2)
.forEach(System.out::println); // Pipeline executes and terminates
Critical Behavior Difference
With peek() alone, nothing happens due to lazy evaluation. With forEach(), execution is guaranteed.
Key Takeaway: Use peek() for intermediate observation and debugging in ongoing pipelines; use forEach() when you're ready to execute and consume the stream with final side effects.