Infinite Streams
suggest changeIt is possible to generate a Stream that does not end. A terminal operation that must visit every element, such as forEach or count, does not finish. Short-circuiting operations such as findFirst can finish once they have a result. The limit method of a Stream can be used to limit the number of terms of the Stream that Java processes.
This example generates an IntStream of the natural numbers, starting at 1. Each successive term is one higher than the previous. Calling limit keeps only the first five terms, which are then printed.
// Generate infinite stream - 1, 2, 3, 4, 5, 6, 7, ...
IntStream naturalNumbers = IntStream.iterate(1, x -> x + 1);
// Print out only the first 5 terms
naturalNumbers.limit(5).forEach(System.out::println);
Output:
1
2
3
4
5
Another way of generating an infinite stream is using the Stream.generate method. This method takes a lambda of type Supplier.
// Generate an infinite stream of random numbers
Stream<Double> infiniteRandomNumbers = Stream.generate(Math::random);
// Print out only the first 10 random numbers
infiniteRandomNumbers.limit(10).forEach(System.out::println);
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents