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

Bounded iterate() with Predicate (Java 9+)

Use the three-argument Stream.iterate() overload with seed, predicate, and function for conditional termination.

Bounded iterate() with Predicate (Java 9+)

You'll learn how to create a finite iteration stream that automatically stops when a condition is met, rather than requiring an external limit() call.

The Three-Argument iterate() Overload

Back in Java 9, the Stream API added a powerful three-argument version of iterate() that combines seed initialization, conditional termination, and element generation in one method:

Stream.iterate(T seed, Predicate<T> hasNext, UnaryOperator<T> next)

This mirrors a traditional for-loop structure:

  • seed: the initial value (like i = 0)
  • hasNext: a predicate that continues iteration while true (like i < 10)
  • next: the function that produces the next element (like i++)

Why It Matters

Previously, you had to call limit() after an infinite iterate() stream. The bounded version is more expressive and safer—it terminates naturally when the predicate returns false.

// Old way: potentially dangerous if forgotten
Stream.iterate(1, n -> n * 2)
      .limit(5)
      .forEach(System.out::println); // 1, 2, 4, 8, 16

// Java 9+: self-limiting, clearer intent
Stream.iterate(1, n -> n <= 16, n -> n * 2)
      .forEach(System.out::println); // 1, 2, 4, 8, 16

Practical Example

// Generate numbers from 0 to 99
Stream.iterate(0, n -> n < 100, n -> n + 1)
      .forEach(System.out::println);

// Countdown sequence
Stream.iterate(10, n -> n >= 0, n -> n - 1)
      .forEach(System.out::println); // 10, 9, 8..., 1, 0

Key Takeaway: Use the three-argument Stream.iterate(seed, predicate, function) when you need conditional termination built into the stream source itself—it's safer and more readable than relying on external limit() calls.