Generator functions equivalent in 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中等效的生成器函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java中等效的生成器函数
基础教程推荐
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
