Java中等效的生成器函数

2022-01-10 00:00:00 python generator iterator java

我想在 Java 中实现一个 Iterator,它的行为有点像 Python 中的以下生成器函数:

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

java 端的

x 可以是多维数组或某种形式的嵌套集合.我不确定这将如何工作.想法?

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?

推荐答案

有同样的需求,所以写了一个小类.以下是一些示例:

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);
    }
};

Generator 类在内部使用线程来生成项目.通过覆盖 finalize(),它可以确保在相应的 Generator 不再使用时不会留下任何线程.

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.

性能显然不是很好,但也不算太差.在我的具有双核 i5 CPU @ 2.67 GHz 的机器上,可以在 < 中生产 1000 个项目.0.03 秒.

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.

代码位于 GitHub.在那里,您还可以找到有关如何将其作为 Maven/Gradle 依赖项包含在内的说明.

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

相关文章