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中等效的生成器函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Reliable implementation of PBKDF2-HMAC-SHA256 for JAVA(PBKDF2-HMAC-SHA256 for JAVA 的可靠实现)
Correct way to sign and verify signature using bouncycastle(使用 bouncycastle 签名和验证签名的正确方法)
Creating RSA Public Key From String(从字符串创建 RSA 公钥)
Why java.security.NoSuchProviderException No such provider: BC?(为什么 java.security.NoSuchProviderException 没有这样的提供者:BC?)
Generating X509 Certificate using Bouncy Castle Java(使用 Bouncy Castle Java 生成 X509 证书)
How can I get a PublicKey object from EC public key bytes?(如何从 EC 公钥字节中获取 PublicKey 对象?)