我在 C# 工作了很长时间,我非常喜欢一种构造,我在这里谈论的是 yield 。由于惰性求值,这甚至可以组织无限的集合:
IEnumerable<int> fib() {
int a = 0, b= 1;
while (true) {
yield return b;
int c = a;
a = b;
b = c+b;
}
}
Java 8 会有类似的语义吗?它会允许全力进行惰性评估吗?
最佳答案
你可以像这样编写一个 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。
关于java - Java 8 会有惰性求值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21553269/