Generator functions equivalent in Java

后端 未结 7 871
后悔当初
后悔当初 2020-12-01 03:50

I would like to implement an Iterator in Java that behaves somewhat like the following generator function in Python:

def iterator(array):
   for         


        
7条回答
  •  自闭症患者
    2020-12-01 03:55

    No, Java does not have "generators" or "yield" per-se, but the same functionality is available by using the Observer Pattern. This is enhanced when using a modern implementation like RxJava. Your code would subscribe to the Obserable and whenever it tries to read the next value from the Observable it would cause it "generate" it's next value. The Observable can maintain it's own state just like a generator for Python or JavaScript. When there are no new values to be read, the "next()" method will block waiting on new data to be available. A good example of this can be found HERE.

提交回复
热议问题