Java 8会有懒惰评估吗?

时间:2014-02-04 13:00:02

标签: java lazy-evaluation yield-return

我在C#工作了很长时间,我非常喜欢一个构造,我在这里谈论 yield return 。由于懒惰的评估,这允许组织甚至无限的集合:

IEnumerable<int> fib() {
  int a = 0, b= 1;
  while (true) {
    yield return b;
    int c = a;
    a = b;
    b = c+b;
  }
}

Java 8是否具有与此类似的语义?它是否会允许懒惰评估它的全部功能?

2 个答案:

答案 0 :(得分:4)

你可以像这样写一个Iterable:

class Fibonacci implements Iterable<Integer> {
  public Iterator<Integer> iterator() {
    return new Iterator<Integer>() {
      private int a = 0, b = 1;

      public boolean hasNext() {
        return true; // also possible to provide a set limit here
      }

      public Integer next() {
        final int lastA = a;
        a = b;
        b = lastA + b;
        return a;
      }

      public void remove() {
        throw new UnsupportedOperationException();
      }
    };
  }
}

然后你可以迭代这样的值:

for (final Integer i : new Fibonacci()) {
  System.out.print(i + ", ");
  if (i > 100) {
    break;
  }
}

所以没有必要等待Java 8。

答案 1 :(得分:3)