3

我正在编写一个代码来计算斐波那契数。使用此代码,我可以生成斐波那契数列的前 n 个数字。

Stream.generate(new Supplier<Long>() {
    private long n1 = 1;
    private long n2 = 2;

    @Override
    public Long get() {
        long fibonacci = n1;
        long n3 = n2 + n1;
        n1 = n2;
        n2 = n3;
        return fibonacci;
    }
}).limit(50).forEach(System.out::println);

该方法limit返回Stream保存传递给此方法的元素数。我想Stream在斐波那契数达到某个值后停止生成。

我的意思是,如果我想列出所有小于 1000 的斐波那契数,那么我不能使用limit,因为我不知道可能有多少斐波那契数。

有没有办法使用 lambda 表达式来做到这一点?

4

4 回答 4

3

The best solution using the Stream’s built-in features I could find is:

LongStream.generate(new LongSupplier() {
  private long n1 = 1, n2 = 2;

  public long getAsLong() {
      long fibonacci = n1;
      long n3 = n2 + n1;
      n1 = n2;
      n2 = n3;
      return fibonacci;
  }
}).peek(System.out::println).filter(x->x>1000).findFirst();

It has the disadvantage of processing the first item being >=1000 though. This can be prevented by making the statement conditional, e.g.

.peek(x->{if(x<=1000) System.out.println(x);}).filter(x->x>1000).findFirst();

but I don’t like to evaluate the same condition (bigger than thousand or not) twice. But maybe one of these two solution might be practical enough for real life tasks where a limit based on the resulting value is needed.

I think, it’s clear that the entire construct is not parallel capable…</p>

于 2014-02-11T19:38:35.317 回答
3

如果您不介意使用迭代器,可以将其写为:

static LongUnaryOperator factorial = x -> x == 0 ? 1
                                      : x * factorial.applyAsLong(x - 1);

public static void main(String[] args) {
    LongStream ls = LongStream.iterate(0, i -> i + 1).map(factorial);
    OfLong it = ls.iterator();
    long next = 0;
    while ((next = it.nextLong()) <= 1000) System.out.println(next);
}
于 2014-02-08T19:29:20.647 回答
2

是的,有一种 lambda 方式,但不幸的是,我认为它没有在当前的 Java 8 StreamAPI 中实现。很抱歉为您指出另一种语言,但我认为您想要的是类似的东西

 takeWhile(p: (A) ⇒ Boolean): Stream[A]

来自 Scala Stream API。

由于这没有在 Java API 中实现,因此您必须自己完成。这个怎么样:

public static List<T> takeWhile(Iterable<T> elements, Predicate<T> predicate) {
   Iterator<T> iter = elements.iterator();
   List<T> result = new LinkedList<T>();
   while(iter.hasNext()) {
     T next = iter.next();
     if (predicate.apply(next)) {
       result.add(next);
     } else {
       return result;  // Found first one not matching: abort
     }
   }
   return result;  // Found end of the elements
}

然后你可以像这样使用它

List<Long> fibNumbersUnderThousand = takeWhile(allFibNumStream, l -> l < 1000);

(假设这Stream是一个实例Iterable- 如果不是,您可能需要调用该.iterator()方法并将其包装起来)

于 2014-02-08T19:03:35.080 回答
1

肮脏的第一个版本

        Stream.generate(new Supplier<Long>() {
        private long n1 = 1;
        private long n2 = 2;

        @Override
        public Long get() {
            long fibonacci = n1;
            long n3 = n2 + n1;
            n1 = n2;
            n2 = n3;
            return fibonacci;
        }
    }).limit(50).forEach(x -> {
        if (x < 1000) {
            System.out.println(x);
        }
    });
于 2014-02-08T18:57:50.463 回答