方法一:使用Stream.iterate()方法生成
//斐波那契数列
Stream.iterate(new int[]{0, 1},
t -> new int[]{t[1], t[0] + t[1]})
.limit(20)
.map(t -> t[0])
.forEach(System.out::println);
*在java9中iterate()支持断言,可以生成小于一个范围内的斐波那契数列
方法二:使用Stram.generate()生成
IntSupplier fib = new IntSupplier() {
private int previous = 0;
private int current = 1;
@Override
public int getAsInt() {
int oldPrevious = this.previous;
int nextValue = this.previous + this.current;
this.previous = this.current;
this.current = nextValue;
return oldPrevious;
}
};
IntStream.generate(fib).limit(10).forEach(System.out::println);