An infinite stream in Java 8 is created with Stream.iterate() or Stream.generate(), both of which produce an unbounded sequence of elements that must be constrained with a short-circuiting operation like limit() before being consumed.
Stream.iterate(0, n -> n + 1).limit(10).forEach(System.out::println) prints the numbers 0 through 9, generated lazily one at a time.
Stream.iterate(0, n -> n + 1)
.limit(10)
.forEach(System.out::println);
Stream.generate(Math::random)
.limit(5)
.forEach(System.out::println);A concise interview answer is
I use Stream.iterate() when each element depends on the previous one, like counting up or computing powers of two, and Stream.generate() when each element is produced independently, like random numbers. Both produce infinite streams, so I always chain a limit() call before a terminal operation, otherwise the pipeline never finishes.
Last updated: 16 July 2026
Previous question: What is the purpose of the Predicate functional interface in Java 8?
Next question: What is the Function interface in Java 8, and how is it used?