Java

Stream.generate / iterate — Infinite Streams

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Build streams from a seed + a function. `generate(supplier)` calls the supplier each time; `iterate(seed, next)` applies a unary op. Always pair with `limit` to bound them.
Java
Raw
import java.util.*;
import java.util.stream.*;

class Demo {
    void example() {
        // generate — same value (or random) on each call
        List<Double> randoms = Stream.generate(Math::random)
            .limit(5)
            .toList();
        System.out.println(randoms);

        // iterate — Fibonacci! Three-arg form has a hasNext predicate (Java 9+)
        List<Long> fibs = Stream.iterate(
                new long[]{0, 1},
                pair -> pair[1] < 1000,                  // hasNext predicate
                pair -> new long[]{pair[1], pair[0] + pair[1]}
            )
            .map(p -> p[0])
            .toList();
        System.out.println(fibs);
        // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987]

        // Or with limit
        List<Integer> powersOf2 = Stream.iterate(1, n -> n * 2)
            .limit(10)
            .toList();
        System.out.println(powersOf2);
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.