Stream.generate()
Creates an infinite stream from the values of a supplier function.
Available since: Java 8
Syntax
static <T> Stream<T> generate(Supplier<? extends T> s)Parameters
| Parameter | Type | Description |
|---|---|---|
| s | Supplier<? extends T> | A no-argument function that produces each next element. |
Return value
Stream<T>An infinite stream.
Examples
A repeated value and seeded random numbers:
void main() {
IO.println(Stream.generate(() -> "ab").limit(3).collect(Collectors.joining()));
Random rnd = new Random(7);
IO.println(Stream.generate(() -> rnd.nextInt(10)).limit(5).toList());
}Output:
ababab
[6, 4, 5, 4, 0]Notes
The stream is infinite: without limit() the terminal operation never finishes. Unlike iterate(), the elements do not depend on each other.
See also
- Stream.iterate() — Creates a stream where each element is computed from the previous one.
- Stream.limit() — Truncates a stream to its first N elements.
- Supplier — A supplier: a no-argument function that returns a value.
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.