Creating Infinite, Lazy Collections
Using infinite collections can make the code that creates a growing series (such as 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 will 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access