Java Reference
In-Depth Information
A basic lazy list
An easy way to adapt this class to the concept of a lazy list is to cause the tail not to be present in
memory all at once but to have a Supplier<T> that you saw in chapter 3 (you can also see it as a
factory with a function descriptor void -> T), which produces the next node of the list. This leads
to the following:
Calling the method get from the Supplier causes the creation of a node of the Lazy-List (as a
factory would create a new object).
You can now create the infinite lazy list of numbers starting at n as follows by passing a Supplier
as the tail argument of the LazyList constructor, which creates the next element in the series of
numbers:
public static LazyList<Integer> from(int n) {
return new LazyList<Integer>(n, () -> from(n+1));
}
If you try the following code for yourself, you'll see that the following calls will print “2 3 4.”
Indeed, the numbers are generated on demand. You can check this by inserting
 
Search WWH ::




Custom Search