Java Reference
In-Depth Information
In this quiz, you need to figure out the highlighted code with the ???. Remember that iterate will
apply the given lambda successively.
Answer:
Stream.iterate(new int[]{0, 1},
t -> new int[]{t[1], t[0]+t[1]})
.limit(20)
.forEach(t -> System.out.println("(" + t[0] + "," + t[1] +")"));
How does it work? iterate needs a lambda to specify the successor element. In the case of the
tuple (3, 5) the successor is (5, 3+5) = (5, 8). The next one is (8, 5+8). Can you see the pattern?
Given a tuple, the successor is (t[1], t[0] + t[1]). This is what the following lambda specifies: t ->
new int[]{t[1],t[0] + t[1]}. By running this code you'll get the series (0, 1), (1, 1), (1, 2), (2, 3), (3,
5), (5, 8), (8, 13), (13, 21).... Note that if you just wanted to print the normal Fibonacci series,
you could use a map to extract only the first element of each tuple:
Stream.iterate(new int[]{0, 1},
t -> new int[]{t[1],t[0] + t[1]})
.limit(10)
.map(t -> t[0])
.forEach(System.out::println);
This code will produce the Fibonacci series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34....
Generate
Similarly to the method iterate, the method generate lets you produce an infinite stream of
values computed on demand. But generate doesn't apply successively a function on each new
produced value. It takes a lambda of type Supplier<T> to provide new values. Let's look at an
example of how to use it:
Stream.generate(Math::random)
.limit(5)
.forEach(System.out::println);
This code will generate a stream of five random double numbers from 0 to 1. For example, one
run gives the following:
Search WWH ::




Custom Search