Question

I was working in C# for a long time, and I liked one construct very much, I am talking about yield return here. This allowed to organize even infinite collections thanks to lazy evaluation:

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

Will Java 8 have a semantics similar to this? Will it allow the lazy evaluation at it's full power?

Was it helpful?

Solution 2

OTHER TIPS

You can write an Iterable like this:

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

Then you can iterate over the values like this:

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

So there is no need to wait for Java 8.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top