我试图通过使用Java来创建fibonacci序列。我已经创建了一个供应商,但我希望它在一个特定的值(例如1000000)停止。
最棒的:
import java.util.function.Supplier;
public class FibonacciSupplier implements Supplier<Integer> {
private int current;
private int next;
public FibonacciSupplier() {
current = 0;
next = 1;
}
@Override
public Integer get() {
int result = current;
current = next + current;
next = result;
return result;
}
}我想要的是:
Stream.generate(new FibonacciSupplier()).maxValue(1000000);maxValue不是作为一个函数存在的,我使用它作为上下文的名称。
发布于 2018-11-07 17:43:14
最好的解决方案是使用takeWhile,这在9+中是可用的:
Stream.generate(new FibonacciSupplier())
.takeWhile(i -> i <= 1000000) //will stop stream when value exceeds given limit
.forEach(System.out::println);如果您使用的是Java 8,那么您可能需要查看hacks for stopping an infinite stream
发布于 2018-11-07 17:34:19
您需要在流中使用.limit()方法,如下所示:
Stream.generate(new FibonacciSupplier()).limit(1000).forEach(System.out::println);从医生那里,
返回由此流的元素组成的流,截断后的流长度不超过{@ maxSize}。
https://stackoverflow.com/questions/53194714
复制相似问题