如何测试它是否是斐波那契流?
How to test if it is a Fibonacci Stream?
这不是斐波那契流。
LongStream digits = LongStream.of(0, 1, 2 , 3 , 4, 5, 6, 7, 8, 9);
这也不是。
LongStream naturals = LongStream.iterate(1, (i) -> i + 1);
但是,你如何检查它们不是?
注意第二个流是无限的,所以你需要一些短路操作来尽快停止。不幸的是,短路方法 'allMatch' 和 'anyMatch' 只测试元素,而不是序列。
使用 Guava Iterables.elementsEqual:
Supplier<Integer> fibonacci = new Supplier<Integer>() {
int first = 0;
int second = 1;
@Override
public Integer get() {
int result = first + second;
first = second;
second = result;
return first;
}
};
boolean isMatch = Iterables.elementsEqual(
toTest,
Stream.generate(fibonacci).limit(toTest.size()).collect(Collectors.toList()));
这不是斐波那契流。
LongStream digits = LongStream.of(0, 1, 2 , 3 , 4, 5, 6, 7, 8, 9);
这也不是。
LongStream naturals = LongStream.iterate(1, (i) -> i + 1);
但是,你如何检查它们不是?
注意第二个流是无限的,所以你需要一些短路操作来尽快停止。不幸的是,短路方法 'allMatch' 和 'anyMatch' 只测试元素,而不是序列。
使用 Guava Iterables.elementsEqual:
Supplier<Integer> fibonacci = new Supplier<Integer>() {
int first = 0;
int second = 1;
@Override
public Integer get() {
int result = first + second;
first = second;
second = result;
return first;
}
};
boolean isMatch = Iterables.elementsEqual(
toTest,
Stream.generate(fibonacci).limit(toTest.size()).collect(Collectors.toList()));