How to create a Java 8 Stream from an iterator?

后端 未结 4 1136
隐瞒了意图╮
隐瞒了意图╮ 2020-12-14 01:14

Is it possible to create a Stream from an Iterator, in which the sequence of objects is the same as that generated by calling the iterator\'s next() method repeatedly? The s

4条回答
  •  借酒劲吻你
    2020-12-14 01:35

    As it was written by Karol Król for infinite stream you can use this:

    Stream.generate(iterator::next)
    

    but you can also use it for finite stream with takeWhile since Java 9

    Stream.generate(iterator::next).takeWhile((v) -> iterator.hasNext())
    

提交回复
热议问题