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

What Is Lazy Evaluation?

Understanding that stream operations don't execute until a terminal operation is invoked.

What Is Lazy Evaluation?

You'll learn: Why intermediate stream operations don't actually do anything until you ask for a final result.

The Core Idea

Lazy evaluation means that intermediate stream operations (like filter(), map(), flatMap()) don't execute immediately when you call them. Instead, they just set up a "recipe" or "plan." The actual work only happens when you invoke a terminal operation (like forEach(), collect(), or reduce()).

Think of it like a restaurant order: when you tell the waiter "I want a salad, no onions, extra dressing," nothing happens in the kitchen yet. The waiter is just writing down your instructions. Only when you say "Please bring it now" (the terminal operation) does the kitchen actually prepare your food.

Why This Matters

Without a terminal operation, your stream pipeline does nothing:

// This looks like it should print something, but it doesn't!
Stream.of(1, 2, 3, 4, 5)
    .filter(n -> n > 2);  // No terminal operation = no execution

// Nothing happens. No filtering occurs. No output.

Only when you add a terminal operation does the work execute:

Stream.of(1, 2, 3, 4, 5)
    .filter(n -> n > 2)
    .forEach(System.out::println);  // NOW it executes: 3, 4, 5

The Efficiency Advantage

Lazy evaluation enables powerful optimizations. The stream can process elements one-by-one through the entire pipeline, avoiding unnecessary work and intermediate storage. It can also short-circuit operations when possible.

Key Takeaway: Intermediate stream operations are lazy—they build a processing plan but don't execute until a terminal operation triggers the pipeline, enabling efficient, on-demand computation.