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

Short-Circuiting with Infinite Streams

Safely working with infinite streams using limit and short-circuiting terminal operations.

Short-Circuiting with Infinite Streams

You'll learn how to safely work with infinite streams by combining limit and short-circuiting terminal operations.

The Core Idea

Infinite streams from Stream.generate() or Stream.iterate() never end on their own—they'll run forever if you let them. Short-circuiting operations are your safety mechanism. They stop processing as soon as they have enough information, preventing infinite execution and making infinite streams practical and safe.

How It Works

Think of it like searching for your keys in an infinitely long hallway. Without short-circuiting, you'd walk forever. With limit(10), you check only the first 10 rooms. With findFirst(), you stop the instant you find them—even if that's in room 3.

When you combine intermediate short-circuiting (like limit() or takeWhile()) with terminal operations, you create a bounded computation from an infinite source:

// Safe: limit() caps the infinite stream at 5 elements
Stream.iterate(1, n -> n + 1)
      .limit(5)
      .forEach(System.out::println);  // Prints 1, 2, 3, 4, 5

// Safe: findFirst() stops after finding one match
Stream.generate(Math::random)
      .filter(n -> n > 0.9)
      .findFirst()  // Stops as soon as one value > 0.9 is found
      .ifPresent(System.out::println);

// Safe: anyMatch() stops at the first true result
boolean hasLargeValue = Stream.iterate(0.0, n -> n + 0.1)
                              .anyMatch(n -> n > 5.0);  // Stops at 5.1

Without short-circuiting, operations like forEach() on an infinite stream would hang your program indefinitely.

Combining Multiple Short-Circuit Operations

You can chain limit() or takeWhile() with short-circuiting terminals like findFirst(), anyMatch(), or allMatch() for extra control and safety.

Key Takeaway: Infinite streams are only safe when you use short-circuiting operations—intermediate ones like limit() to bound the stream, or terminal ones like findFirst() and anyMatch() that stop early. Never apply non-short-circuiting terminals to unbounded streams.