我在使用流来生成一个包含斐波那契数列中所有数字的无限大小、顺序流方面遇到了一些问题。
如何打印出无限流?任何建议都有帮助,谢谢。
public class Fibonacci {
public static void main(String[] args) {
IntStream stream = IntStream.generate(new FibonacciSupplier());
stream.limit(20).forEach(System.out::println);
}
private static class FibonacciSupplier implements IntSupplier {
int current = 1;
int previous = 0;
@Override
public int getAsInt() {
int result = current;
current = previous + current;
previous = result;
return result;
}
}
}
需要注意的是,一旦达到第47个元素,这个流就不可能是无限的,因为该值太大而无法适应正整数。
map
操作来生成序列。但事实上不行:Java非终端操作只能一次处理一个元素。这使得它们可以转换为具有确定性结果的并行流。class Fib {
private int previous = 0;
private int current = 1;
private int next() {
int temp = previous + current;
previous = current;
current = temp;
return current;
}
public IntStream stream() {
return IntStream.generate(this::next);
}
}
可以使用new Fib().stream()
来实现。
您也可以仅使用数组来完成此操作:
IntStream fibStream = Stream.iterate(new int[]{0, 1}, a -> new int[]{a[1], a[0]+a[1]}).mapToInt(a -> a[1])
// print first 20 fibonacci number
fibStream.limit(20).forEach(System.out::println);