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

Infinite Streams and Laziness

Seeing how lazy evaluation enables working with infinite streams like Stream.iterate.

Infinite Streams and Laziness

You'll learn how lazy evaluation makes infinite streams not only possible but practical in Java.

Understanding Infinite Streams

An infinite stream is exactly what it sounds like: a stream with no defined end. You've already seen Stream.generate() and Stream.iterate() that can produce endless sequences. Without laziness, attempting to work with infinite data would be catastrophic—your program would never finish computing all elements before doing anything useful.

How Laziness Enables Infinity

Because intermediate operations are lazy, they don't process all elements immediately. Instead, they wait for a terminal operation to demand values, then produce elements only as needed. When you limit an infinite stream (like with limit()), the pipeline knows exactly when to stop pulling elements.

Think of it like a water tap: you could theoretically run water forever, but by holding a cup underneath, you signal exactly how much you need. The tap doesn't fill an infinite bucket first—it provides water on demand until your cup is full.

Practical Example

Stream.iterate(1, n -> n + 1)  // Infinite sequence: 1, 2, 3, 4...
      .filter(n -> n % 2 == 0)  // Even numbers only (still infinite, still lazy)
      .limit(5)                 // First 5 even numbers
      .forEach(System.out::println);  // Terminal: triggers execution

This works because:

  1. iterate() doesn't generate all numbers upfront
  2. filter() doesn't test infinite values—it waits
  3. limit(5) tells the pipeline to stop after 5 results
  4. forEach() pulls elements one by one until the limit is reached

Without laziness, the filter() operation would try to examine infinite numbers before limit() ever got a say.

Key Takeaway:
Lazy evaluation transforms infinite streams from impossible to practical—operations execute only when needed and stop as soon as a terminal operation is satisfied.