Generator functions equivalent in Java

Eqbal picture Eqbal · Jul 20, 2012 · Viewed 51.2k times · Source

I would like to implement an Iterator in Java that behaves somewhat like the following generator function in Python:

def iterator(array):
   for x in array:
      if x!= None:
        for y in x:
          if y!= None:
            for z in y:
              if z!= None:
                yield z

x on the java side can be multi-dimensional array or some form of nested collection. I am not sure how this would work. Ideas?

Answer

Michael Herrmann picture Michael Herrmann · Jan 7, 2014

Had the same need so wrote a little class for it. Here are some examples:

Generator<Integer> simpleGenerator = new Generator<Integer>() {
    public void run() throws InterruptedException {
        yield(1);
        // Some logic here...
        yield(2);
    }
};
for (Integer element : simpleGenerator)
    System.out.println(element);
// Prints "1", then "2".

Infinite generators are also possible:

Generator<Integer> infiniteGenerator = new Generator<Integer>() {
    public void run() throws InterruptedException {
        while (true)
            yield(1);
    }
};

The Generator class internally works with a Thread to produce the items. By overriding finalize(), it ensures that no Threads stay around if the corresponding Generator is no longer used.

The performance is obviously not great but not too shabby either. On my machine with a dual core i5 CPU @ 2.67 GHz, 1000 items can be produced in < 0.03s.

The code is on GitHub. There, you'll also find instructions on how to include it as a Maven/Gradle dependency.