問題描述
我想在 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中等效的生成器函數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!