Stream.iterate() with predicate
Use a predicate to stop iteration — like a for-loop in stream form.
Porównanie kodu
✕ 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(IO::println);
// stops when n >= 1000
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
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.
Stare podejście
iterate + limit
Nowoczesne podejście
iterate(seed, pred, op)
Od JDK
9
Poziom trudności
Średniozaawansowany
Wsparcie JDK
Stream.iterate() with predicate
Dostępne
Widely available since JDK 9 (Sept 2017)
Jak to działa
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.
Powiązana dokumentacja