是否有一个Java等同于C#的'yield'关键字?

是否有一个Java等同于C#的'yield'关键字?

问题描述:

我知道Java本身没有直接的等价物,但也许是第三方?

I know there is no direct equivalent in Java itself, but perhaps a third party?

这真的很方便。目前我想实现一个迭代器,它产生一个树中的所有节点,大约有五行代码和yield。

It is really convenient. Currently I'd like to implement an iterator that yields all nodes in a tree, which is about five lines of code with yield.

我所知道的两个选项是 2007年Aviad Ben Dov的infomancers-collections图书馆 Jim Blackler的2008年YieldAdapter图书馆(其他答案中也提到了这一点) )。

The two options I know of is Aviad Ben Dov's infomancers-collections library from 2007 and Jim Blackler's YieldAdapter library from 2008 (which is also mentioned in the other answer).

两者都允许你用Java编写带有 yield return -like构造的代码,所以两者都会满足你的申请。两者之间的显着差异是:

Both will allow you to write code with yield return-like construct in Java, so both will satisfy your request. The notable differences between the two are:

Aviad的库使用字节码操作,而Jim使用多线程。根据您的需要,每个人都有自己的优点和缺点。可能Aviad的解决方案更快,而Jim更便携(例如,我不认为Aviad的库可以在Android上运行)。

Aviad's library is using bytecode manipulation while Jim's uses multithreading. Depending on your needs, each may have its own advantages and disadvantages. It's likely Aviad's solution is faster, while Jim's is more portable (for example, I don't think Aviad's library will work on Android).

Aviad的库有一个更干净的界面 - 这是一个例子:

Aviad's library has a cleaner interface - here's an example:

Iterable<Integer> it = new Yielder<Integer>() {
    @Override protected void yieldNextCore() {
        for (int i = 0; i < 10; i++) {
            yieldReturn(i);
            if (i == 5) yieldBreak();
        }
    }
};

虽然Jim更复杂,但要求你熟练一个通用的收集器,它有一个 collect(ResultHandler)方法......呃。但是,您可以使用这个包装缩放信息的Jim代码包装器,这大大简化了:

While Jim's is way more complicated, requiring you to adept a generic Collector which has a collect(ResultHandler) method... ugh. However, you could use something like this wrapper around Jim's code by Zoom Information which greatly simplifies that:

Iterable<Integer> it = new Generator<Integer>() {
    @Override protected void run() {
        for (int i = 0; i < 10; i++) {
            yield(i);
            if (i == 5) return;
        }
    }
};



许可证



Aviad的解决方案是BSD。

License

Aviad's solution is BSD.

Jim的解决方案是公共领域,上面提到的包装器也是如此。

Jim's solution is public domain, and so is its wrapper mentioned above.