为流生成提供限制条件 [英] Providing Limit condition on Stream generation

查看:104
本文介绍了为流生成提供限制条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am writing a code to calculate Fibonacci numbers. With this code I can generate first n numbers of the Fibonacci sequence.

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 ,它包含传递给此方法的元素数。我希望在Fibonacci数达到某个值后停止生成 Stream

The method limit returns the Stream which holds the number of elements passed to this method. I want to stop the generation of the Stream after the Fibonacci number reached some value.

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

I mean if I want to list all Fibonacci numbers less than 1000 then I cannot use limit, because I don't know how many Fibonacci numbers there could be.

有没有办法用lambda表达式做这个?

Is there any way to do this using lambda expressions?

推荐答案

使用我能找到的 Stream 的内置功能的最佳解决方案是:

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();

它的缺点是处理第一项> = 1000 但是。这可以通过使语句成为条件来防止,例如

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…

这篇关于为流生成提供限制条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆