Java Reference
In-Depth Information
System.out.println appropriately or just by noting that from(2)would run forever if it tried to
eagerly calculate all the numbers starting from 2!
LazyList<Integer> numbers = from(2);
int two = numbers.head();
int three = numbers.tail().head();
int four = numbers.tail().tail().head();
System.out.println(two + " " + three + " " + four);
Back to generating primes
See if you can use what you've done so far to generate a self-defining lazy list of prime numbers
(something you were unable to do with the Streams API). If you were to translate the code that
was using the Streams API earlier using our new LazyList, it would look like something like this:
public static MyList<Integer> primes(MyList<Integer> numbers) {
return new LazyList<>(
numbers.head(),
() -> primes(
numbers.tail()
.filter(n -> n % numbers.head() != 0)
)
);
}
Implementing a lazy filter
Unfortunately, a LazyList (more accurately the List interface) doesn't define a filter method, so
the previous code won't compile! Let's fix this and declare one:
Your code now compiles and is ready for use! You can calculate the first three prime numbers by
chaining calls to tail and head:
 
Search WWH ::




Custom Search