Stream.iterate() with predicate
Use a predicate to stop iteration — like a for-loop in stream form.
Code Comparison
✕ Java 8
Stream.iterate(1, n -> n * 2)
.limit(10)
.forEach(System.out::println);
// can't stop at a condition
✓ Java 9+
Stream.iterate(
1,
n -> n < 1000,
n -> n * 2
).forEach(System.out::println);
// stops when n >= 1000
Why the modern way wins
Natural termination
Stop based on a condition, not an arbitrary limit.
For-loop equivalent
Same semantics as for(seed; hasNext; next).
No infinite stream risk
The predicate guarantees termination.
Old Approach
iterate + limit
Modern Approach
iterate(seed, pred, op)
Since JDK
9
Difficulty
intermediate
JDK Support
Stream.iterate() with predicate
Available
Widely available since JDK 9 (Sept 2017)
How it works
The three-argument Stream.iterate(seed, hasNext, next) works like a for-loop: seed is the start, hasNext determines when to stop, and next produces the next value.