Stream.iterate()
Creates a stream where each element is computed from the previous one.
Available since: Java 8
Syntax
static <T> Stream<T> iterate(T seed, UnaryOperator<T> f)
static <T> Stream<T> iterate(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next)Parameters
| Parameter | Type | Description |
|---|---|---|
| seed | T | The first element. |
| hasNext | Predicate<? super T> | Optional condition to continue (Java 9). |
| next | UnaryOperator<T> | Computes the next element from the previous one. |
Return value
Stream<T>A sequential stream.
Examples
Powers of two with a stop condition:
void main() {
Stream.iterate(1, n -> n <= 100, n -> n * 2)
.forEach(n -> IO.print(n + " "));
IO.println("");
}Output:
1 2 4 8 16 32 64An infinite stream limited by limit():
void main() {
List<String> labels = Stream.iterate(1, n -> n + 1)
.limit(4)
.map(n -> "Item " + n)
.toList();
IO.println(labels);
}Output:
[Item 1, Item 2, Item 3, Item 4]Notes
The two-argument version is infinite — always limit it with limit() or takeWhile(), or the program hangs. The version with a condition works like a for (seed; hasNext; next) loop.
See also
- Stream.generate() — Creates an infinite stream from the values of a supplier function.
- Stream.limit() — Truncates a stream to its first N elements.
- Stream.takeWhile() — Takes elements while a condition holds and stops at the first one that fails it.
Related recipes
In the tutorial
- What a stream is — The Java Stream API — the source, intermediate and terminal operations, creating streams, lazy evaluation and why a stream can be used only once.