How to create a Java 8 Stream from an iterator?

后端 未结 4 1142
隐瞒了意图╮
隐瞒了意图╮ 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:43

    This doesn't create a stream, but Iterator also has a method called forEachRemaining:

    someIterator.forEachRemaining(System.out::println);
    someIterator.forEachRemaining(s -> s.doSomething());
    //etc.
    

    The argument you pass in is a Consumer which is the same thing you pass to Stream::forEach.

    Here are the docs for that method. note that you can't continue the "chain" like you can with a stream. But I've still found this helpful the few times I've wanted a Stream from an Iterator.

提交回复
热议问题