Creating Infinite, Lazy Collections
Infinite collections can make the code to create a growing series, like the Fibonacci numbers, clearer and easier to express. But from our experience in Java, we might think a series can’t be infinite due to practical memory limits. The laziness of Streams comes in again here.
In Java, collections are still required to be finite but streams can be infinite. We’ll see here how laziness becomes an essential workhorse to make infinite streams possible. We’ll use them to create highly expressive, easy-to-understand code to produce an infinitely growing series.
A Desperate Attempt
We’ll use a series of prime numbers, 2, 3, 5, 7,… as an example to explore the concepts here. Let’s first create a helper function to ...