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
- flatMap for Nested Collections
- Parallel Streams: Performance and Pitfalls
- Spliterator: Splitting for Parallelism
- Infinite Streams with iterate and generate