Java Reference ยท Streams and Functional
Java Stream.iterate() and generate()
Reference for Java Stream.iterate() and Stream.generate(): build infinite or bounded sequences from a seed, with the three-argument form (Java 9).
Stream.iterate() builds a sequence from a seed and a function that produces each next element from the previous one: seed, f(seed), f(f(seed)), and so on. The two-argument form is infinite, so you must limit it with limit(), takeWhile() or a short-circuiting terminal such as findFirst().
Java 9 added a three-argument form with a hasNext predicate, which works like a classic for loop and ends by itself. Stream.generate(supplier) is the related factory for sequences that do not depend on the previous element.
Stream.iterate(1, n -> n * 2).limit(5); // 1, 2, 4, 8, 16 Stream.iterate(0, n -> n < 10, n -> n + 3); // 0, 3, 6, 9
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
static <T> Stream<T> iterate(T seed, UnaryOperator<T> next) static <T> Stream<T> iterate(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next) static <T> Stream<T> generate(Supplier<? extends T> s)
| Name | Description |
|---|---|
seed |
The first element. |
hasNext |
Three-argument form only: while it returns true the element is produced; the stream ends at the first false. |
next |
Computes the next element from the previous one. |
s |
For generate(): supplies each element. |
Returns: a sequential, ordered Stream<T> (iterate) or an unordered one (generate).
Usage notes
- Always bound the two-argument forms.
Stream.iterate(1, n -> n + 1).forEach(...)never ends. - Lazy:
nextis called only when an element is needed, solimit(n)calls it aboutn - 1times. - Predicate vs
takeWhile: the three-argument form tests the seed too and never callsnextafter the end; withtakeWhilethe next value was already computed. - Stateful suppliers:
generate()with a counter works only sequentially. For numbers, preferIntStream.range()orIntStream.iterate(). - Primitive versions:
IntStream.iterate,LongStream.iterateandDoubleStream.iterateavoid boxing. - Overflow:
intsequences wrap silently; uselongorBigIntegerfor fast-growing sequences. - Seed is shared: if the seed is a mutable object,
nextshould return a new one, as the Fibonacci example does.