Java中等效的生成器函数

Generator functions equivalent in Java(Java中等效的生成器函数)
本文介绍了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.

这篇关于Java中等效的生成器函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)