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.

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);

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