Stream.iterate() starts with a seed (the first argument) and passes it to the method (the second argument). The result is added to the stream and also stored for use as the first argument the next time iterate() is called, and so on.
// streams/Fibonacci.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import java.util.stream.*;
public class Fibonacci {
int x = 1;
Stream<Integer> numbers() {
return Stream.iterate(
0,
i -> {
int result = x + i;
System.out.println("i:" + i + ", " + x);
x = i;
// System.out.println("i:" + i + ", " + x);
return result;
});
}
public static void main(String[] args) {
new Fibonacci()
.numbers()
.skip(20) // Don't use the first 20
.limit(10) // Then take 10 of them
.forEach(System.out::println);
}
}
/* Output:
6765
10946
17711
28657
46368
75025
121393
196418
317811
514229
*/
My output:
i:0, 1
i:1, 0
i:1, 1
i:2, 1
i:3, 2
i:5, 3
i:8, 5
i:13, 8
i:21, 13
i:34, 21
i:55, 34
i:89, 55
i:144, 89
i:233, 144
i:377, 233
i:610, 377
i:987, 610
i:1597, 987
i:2584, 1597
i:4181, 2584
6765
i:6765, 4181
10946
i:10946, 6765
17711
i:17711, 10946
28657
i:28657, 17711
46368
i:46368, 28657
75025
i:75025, 46368
121393
i:121393, 75025
196418
i:196418, 121393
317811
i:317811, 196418
514229
The Fibonacci sequence sums the last two elements in the sequence to produce the next one. iterate() only remembers the result, so we must use x to keep track of the other element.
references:
1. On Java 8 - Bruce Eckel
2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/streams/Fibonacci.java
4. https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#skip-long-