生成器函数在Java中等效 [英] Generator functions equivalent in 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);
}
};
生成器
类内部使用线程生产这些物品。通过重写 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的机器上,可以在< 0.03s。
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中等效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!