Is there a Java equivalent to C#'s 'yield' keyword?

前端 未结 6 1108
自闭症患者
自闭症患者 2020-11-27 11:36

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

It is really convenient. Currently I\'d like to implement an iterator that yields all

6条回答
  •  时光取名叫无心
    2020-11-27 12:14

    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).

    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:

    Mechanics

    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).

    Interface

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

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

    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 it = new Generator() {
        @Override protected void run() {
            for (int i = 0; i < 10; i++) {
                yield(i);
                if (i == 5) return;
            }
        }
    };
    

    License

    Aviad's solution is BSD.

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

提交回复
热议问题