Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 nodes in a tree, which is about five lines of code with yield.

like image 857
ripper234 Avatar asked Dec 30 '09 16:12

ripper234


People also ask

Is C# equivalent to Java?

Java and C# are incredibly similar. Both languages are somewhat derived from C++ and from similar first principles. Java was developed in 1995 to create a language with a simpler programming model than C++ while still preserving some of the same syntax of the language to facilitate developers transitioning to it.

What is the equivalent of pointers in Java?

Java doesn't have pointers; Java has references.

What is char* in Java?

The char keyword is a data type that is used to store a single character. A char value must be surrounded by single quotes, like 'A' or 'c'.

What is lower bound in Java?

Lower-bound is when you specify (? super Field) means argument can be any Field or superclass of Field. Try following code: Uncomment the code and check if any error comes. import java.util.ArrayList; import java.util.Collection; public class GenericsDemo { public static void validateTillStringType(Collection<?


1 Answers

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<Integer> it = new Yielder<Integer>() {     @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<Integer> it = new Generator<Integer>() {     @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.

like image 102
Oak Avatar answered Sep 28 '22 11:09

Oak