0Pricing
Java Academy · Lesson

Infinite Streams with iterate and generate

Create infinite streams with Stream.iterate and Stream.generate, then limit or take-while to stop.

Infinite Streams with iterate and generate is a free Java Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What Are Infinite Streams?

Java Streams can be infinite — they produce elements on demand with no end. They must be terminated with a limiting operation (limit, takeWhile, findFirst, etc.) to avoid running forever.

Stream.iterate: Seeded Sequences

Stream.iterate(seed, f) generates an infinite stream by repeatedly applying f to the previous value. The first element is the seed.

// Infinite even numbers: 0, 2, 4, 6, 8, ...
Stream.iterate(0, n -> n + 2)
    .limit(10)
    .forEach(System.out::println);

iterate with Predicate (Java 9+)

Stream.iterate(seed, predicate, f) adds a stopping condition — like a for-loop with a condition. The stream stops when the predicate is false.

// Equivalent to: for (int i = 1; i <= 100; i *= 2)
Stream.iterate(1, n -> n <= 100, n -> n * 2)
    .forEach(System.out::println); // 1 2 4 8 16 32 64

Stream.generate: Stateless Generator

Stream.generate(Supplier) calls the supplier for each element. The supplier can be stateless (random numbers) or stateful (using an external counter).

// Infinite random doubles between 0.0 and 1.0:
Stream.generate(Math::random)
    .limit(5)
    .forEach(System.out::println);

Generating UUIDs

Use generate with UUID::randomUUID to create a stream of unique identifiers for batch ID generation.

List<String> ids = Stream.generate(() -> UUID.randomUUID().toString())
    .limit(100)
    .collect(Collectors.toList());
System.out.println(ids.size()); // 100

Fibonacci with iterate

Generate Fibonacci numbers using a pair state. Java 9's two-arg iterate makes this elegant.

Stream.iterate(new long[]{0, 1}, p -> new long[]{p[1], p[0]+p[1]})
    .limit(10)
    .map(p -> p[0])
    .forEach(System.out::println); // 0 1 1 2 3 5 8 13 21 34

takeWhile and dropWhile (Java 9+)

takeWhile(predicate) takes elements while the predicate holds, then stops. dropWhile skips elements until the predicate fails, then takes the rest.

// takeWhile stops at the first element where predicate is false:
Stream.iterate(1, n -> n + 1)
    .takeWhile(n -> n < 10)
    .forEach(System.out::println); // 1 2 3 4 5 6 7 8 9

Infinite Streams for Retry Polling

Model a polling loop with generate: generate check results, takeWhile the condition is not met, then take the first success.

Optional<String> result = Stream.generate(() -> checkJobStatus(jobId))
    .takeWhile(status -> status.equals("PENDING"))
    .findFirst();
// When job completes, takeWhile stops and findFirst gets "DONE"

IntStream.range and rangeClosed

For finite integer sequences, IntStream.range(start, end) and rangeClosed(start, end) are more efficient than iterate.

// Sum 1 to 1000:
int sum = IntStream.rangeClosed(1, 1000).sum();
System.out.println(sum); // 500500

LongStream.iterate for Long Sequences

Use LongStream.iterate for long sequences to avoid autoboxing overhead of Stream<Long>.

long sumOfPrimes = LongStream.iterate(2, n -> n + 1)
    .filter(n -> isPrime(n))
    .limit(1000)
    .sum();

Infinite Streams Are Lazy

Infinite streams do not precompute elements. Each element is generated only when the terminal operation requests it. This laziness makes infinite streams practical.

Quick Check

What stopping mechanism is required when working with an infinite stream?

Recap

iterate(seed, f) for sequences, generate(supplier) for independent element generation. Always add a short-circuit terminal (limit, takeWhile, findFirst). Infinite streams are lazy — only materialized on demand.

Frequently asked questions

Is the “Infinite Streams with iterate and generate” lesson free?

Yes — the full text of “Infinite Streams with iterate and generate” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.

What will I learn in “Infinite Streams with iterate and generate”?

Create infinite streams with Stream.iterate and Stream.generate, then limit or take-while to stop. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Java Academy?

No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Infinite Streams with iterate and generate” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Java Academy lesson?

Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. flatMap for Nested Collections
  2. Parallel Streams: Performance and Pitfalls
  3. Spliterator: Splitting for Parallelism
  4. Infinite Streams with iterate and generate
← Back to Java Academy