Skip to lesson

Stream.iterate and Stream.generate

Stream.iterate builds a stream where each value is made from the one before it, and Stream.generate builds a stream where each value comes fresh from a Supplier. Both can go on forever, so every pipeline that uses them needs something that stops it.

Infinite streams with Stream.iterate and a seed

Stream.iterate(seed, f) starts with the seed, the first value, and then applies the function f to the previous value again and again: seed, f(seed), f(f(seed)), and so on. Stream.iterate(1, n -> n * 2) gives 1, 2, 4, 8, 16 without end.

Example 1 · iterate: each value from the one before

IterateDemo.javaJava
import java.util.stream.IntStream;import java.util.stream.Stream;
public class IterateDemo {    public static void main(String[] args) {        int n = 1;        int printed = 0;        while (printed < 8) {            System.out.print(n + " ");            n = n * 2;            printed++;        }        System.out.println();
        System.out.println(Stream.iterate(1, x -> x * 2).limit(8).toList());
        // count down by 15 minutes before an exam starts        System.out.println(IntStream.iterate(60, m -> m - 15).limit(5).boxed().toList());
        // first power of 3 above 1000        System.out.println(IntStream.iterate(1, x -> x * 3).filter(x -> x > 1000).findFirst().getAsInt());    }}
Output
1 2 4 8 16 32 64 128
[1, 2, 4, 8, 16, 32, 64, 128]
[60, 45, 30, 15, 0]
2187

What this code does

  • Stream.iterate(1, x -> x * 2) is endless, but limit(8) takes eight values and stops. The loop needs two extra variables to do the same.
  • findFirst() also stops the flow: after filter passes 2187 it needs nothing more. Here filter is safe because findFirst ends the stream.

The old way is a while loop with a variable that changes each round. The stream version puts the start and the rule in one line, and the caller decides how many values to take. An endless stream is safe because streams are lazy: a value is made only when the next step asks for it. limit(10) asks for 10 and then stops. findFirst, anyMatch and takeWhile also stop the flow. IntStream.iterate, LongStream.iterate and DoubleStream.iterate do the same with plain numbers.

iterate with a stop condition (Java 9)

Since Java 9 there is a three-part form: Stream.iterate(seed, hasNext, next). It reads exactly like a for loop.

Example 2 · Three-part iterate for a fee plan

FeePlanDemo.javaJava
import java.util.stream.IntStream;
public class FeePlanDemo {    public static void main(String[] args) {        int fee = 50000;        int instalment = 12000;
        // for-loop version        for (int left = fee; left > 0; left -= instalment) {            System.out.print(left + " ");        }        System.out.println();
        // Java 9: seed, condition, next        IntStream.iterate(fee, left -> left > 0, left -> left - instalment)                .forEach(left -> System.out.print(left + " "));        System.out.println();
        long payments = IntStream.iterate(fee, left -> left > 0, left -> left - instalment).count();        System.out.println("Number of instalments: " + payments);    }}
Output
50000 38000 26000 14000 2000
50000 38000 26000 14000 2000
Number of instalments: 5

What this code does

  • The three parts match the for loop header: start at 50000, go on while the amount left is above 0, subtract 12000 each time.
  • The condition is checked before each value, so the stream ends after 2000 and count() finishes. The last instalment covers only the 2000 that is left.

Example 3 · Fibonacci numbers with an array as the state

FibonacciDemo.javaJava
import java.util.stream.Stream;
public class FibonacciDemo {    public static void main(String[] args) {        // each element is a pair {current, next}        System.out.println(                Stream.iterate(new long[] {0, 1}, p -> new long[] {p[1], p[0] + p[1]})                        .limit(12)                        .map(p -> p[0])                        .toList());
        long firstAboveMillion = Stream.iterate(new long[] {0, 1}, p -> new long[] {p[1], p[0] + p[1]})                .map(p -> p[0])                .filter(f -> f > 1_000_000)                .findFirst()                .get();        System.out.println("First Fibonacci above a million: " + firstAboveMillion);    }}
Output
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
First Fibonacci above a million: 1346269

What this code does

  • A Fibonacci number needs the two before it, so each element is a small pair. The rule builds a new pair {next, current + next}; nothing outside the lambda changes.
  • map(p -> p[0]) keeps only the first number of each pair. findFirst() returns an Optional, and get() is safe because a value above a million always comes.

IntStream.iterate(1, i -> i <= 100, i -> i * 3) is the same as for (int i = 1; i <= 100; i *= 3) and gives 1, 3, 9, 27, 81.

The condition is checked before each value, including the seed. The stream ends the first time the condition is false, so it is not infinite. Use this form when the end is a condition on the value ("while the balance is above zero") rather than a count ("the first 10"). takeWhile(condition) on a two-part iterate gives the same result. The three-part form is shorter and keeps the start, the stop and the step in one place.

Stream.generate with a Supplier

Stream.generate(supplier) calls the Supplier again for every element. Each value does not depend on the one before, so it fits random values, fixed values and test data: Stream.generate(() -> "-").limit(30) makes a line of 30 dashes.

Example 4 · generate: OTPs and test data from a seeded Random

GenerateDemo.javaJava
import java.util.List;import java.util.Random;import java.util.stream.Collectors;import java.util.stream.Stream;
public class GenerateDemo {    public static void main(String[] args) {        Random random = new Random(2024);   // fixed seed: same numbers every run
        List<Integer> otps = Stream.generate(() -> 100000 + random.nextInt(900000))                .limit(3)                .toList();        System.out.println("Test OTPs: " + otps);
        List<Integer> marks = Stream.generate(() -> 35 + random.nextInt(66))                .limit(5)                .toList();        System.out.println("Sample marks: " + marks);
        String line = Stream.generate(() -> "=").limit(20).collect(Collectors.joining());        System.out.println(line);    }}
Output
Test OTPs: [719050, 946626, 367186]
Sample marks: [93, 40, 70, 40, 46]
====================

What this code does

  • Stream.generate calls the Supplier once per element. 100000 + nextInt(900000) always gives a 6-digit number, and 35 + nextInt(66) gives marks from 35 to 100.
  • The seed 2024 makes the numbers the same on every run, which is what tests need. A fixed supplier such as () -> "=" repeats one value.

For random values, pass in a Random object. A Random made with a seed, such as new Random(2024), gives the same numbers every run. That is what you want for tests and for examples: the result can be checked. A real OTP service uses an unseeded, secure generator instead, so nobody can predict the next code. When each value depends on the previous one, such as a counter, use iterate. A generate supplier that changes an outside counter is a side effect, which the next lesson explains.

For real one-time passwords, Java offers java.security.SecureRandom; the seeded Random here is only for repeatable practice data.

Trap: an infinite stream without limit never ends

A terminal operation such as forEach, count, toList or sum wants every element. On an infinite stream with no limit, it never finishes. The program does not crash; it just hangs, or runs until memory is full.

Example 5 · Trap: filter does not stop an infinite stream

StopCorrectlyDemo.javaJava
import java.util.stream.Stream;
public class StopCorrectlyDemo {    public static void main(String[] args) {        // never ends: filter keeps looking for more values below 100        // Stream.iterate(1, n -> n * 2).filter(n -> n < 100).forEach(System.out::println);
        System.out.println("takeWhile:  "                + Stream.iterate(1, n -> n * 2).takeWhile(n -> n < 100).toList());
        System.out.println("3-part:     "                + Stream.iterate(1, n -> n < 100, n -> n * 2).toList());
        System.out.println("limit then filter: "                + Stream.iterate(1, n -> n + 1).limit(10).filter(n -> n % 3 == 0).toList());        System.out.println("filter then limit: "                + Stream.iterate(1, n -> n + 1).filter(n -> n % 3 == 0).limit(10).toList());    }}
Output
takeWhile:  [1, 2, 4, 8, 16, 32, 64]
3-part:     [1, 2, 4, 8, 16, 32, 64]
limit then filter: [3, 6, 9]
filter then limit: [3, 6, 9, 12, 15, 18, 21, 24, 27, 30]

What this code does

  • The commented line prints 1 to 64 and then hangs: filter cannot know that no later power of 2 is below 100. takeWhile and the three-part iterate stop at the first value that fails.
  • Where limit sits changes the answer. Limit first means "look at 10 values"; filter first means "find 10 matches". Both end, because limit is there.

filter does not stop a stream. Stream.iterate(1, n -> n * 2).filter(n -> n < 100).forEach(...) prints 1 to 64 and then waits forever, because filter keeps checking values in case a later one passes. To stop at the first value that fails, use takeWhile or the three-part iterate. Two more hangs: sorted() must see every element before it outputs one, so it hangs even with a limit after it. And distinct().limit(7) on dice rolls hangs too, because there are only six different values to find.

Next step

Check your understanding

11 quick questions