Course contentsShow
← Java
Lesson 1405 of 2,87031. Streams API: Creation and BasicsFree lesson

Demonstrating Lazy Evaluation with Side Effects

Using println in intermediate operations to observe when elements are actually processed.

Demonstrating Lazy Evaluation with Side Effects

You'll learn how to use println in intermediate operations to visually prove that streams only process elements when a terminal operation demands them.

Seeing Is Believing

We've talked about lazy evaluation conceptually—intermediate operations don't execute until a terminal operation kicks in. But how can you see this in action? The simplest way is to add side effects (like System.out.println) inside your intermediate operations. While side effects should be avoided in production stream code, they're incredibly useful for learning and debugging.

Adding println to Observe Execution

When you insert a println statement in an intermediate operation like map or filter, you can watch exactly when each element flows through the pipeline:

Stream.of("apple", "banana", "cherry")
    .filter(s -> {
        System.out.println("filtering: " + s);
        return s.startsWith("a");
    })
    .map(s -> {
        System.out.println("mapping: " + s);
        return s.toUpperCase();
    })
    .forEach(System.out::println);

Output:

filtering: apple
mapping: apple
APPLE
filtering: banana
filtering: cherry

Notice how each element is filtered, then immediately mapped (if it passes), then printed by forEach. The stream doesn't filter all elements first, then map all results—it processes one element through the entire pipeline before moving to the next. This is lazy, element-by-element execution.

Why This Matters

Without the terminal forEach, those println statements would never execute. Try removing it—nothing prints! This proves intermediate operations are truly lazy.

Key Takeaway:
Using System.out.println inside intermediate operations reveals that streams process elements lazily, one at a time through the pipeline, only when triggered by a terminal operation.