小编典典

如何将迭代器转换为流?

all

我正在寻找一种简洁的方法来将 a
转换Iterator
aStream或更具体地说是将迭代器“查看”为流。

出于性能原因,我想避免在新列表中复制迭代器:

Iterator<String> sourceIterator = Arrays.asList("A", "B", "C").iterator();
Collection<String> copyList = new ArrayList<String>();
sourceIterator.forEachRemaining(copyList::add);
Stream<String> targetStream = copyList.stream();

根据评论中的一些建议,我也尝试使用Stream.generate

public static void main(String[] args) throws Exception {
    Iterator<String> sourceIterator = Arrays.asList("A", "B", "C").iterator();
    Stream<String> targetStream = Stream.generate(sourceIterator::next);
    targetStream.forEach(System.out::println);
}

但是,我得到一个NoSuchElementException(因为没有调用hasNext

Exception in thread "main" java.util.NoSuchElementException
    at java.util.AbstractList$Itr.next(AbstractList.java:364)
    at Main$$Lambda$1/1175962212.get(Unknown Source)
    at java.util.stream.StreamSpliterators$InfiniteSupplyingSpliterator$OfRef.tryAdvance(StreamSpliterators.java:1351)
    at java.util.Spliterator.forEachRemaining(Spliterator.java:326)
    at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580)
    at Main.main(Main.java:20)

我看过,StreamSupportCollections我没有找到任何东西。


阅读 123

收藏
2022-03-08

共1个答案

小编典典

一种方法是从中创建一个Spliterator并将Iterator其用作流的基础:

Iterator<String> sourceIterator = Arrays.asList("A", "B", "C").iterator();
Stream<String> targetStream = StreamSupport.stream(
          Spliterators.spliteratorUnknownSize(sourceIterator, Spliterator.ORDERED),
          false);

另一种可能更具可读性的替代方法是使用- 并且使用 lambdas从
anIterable创建一个非常容易,因为它是一个函数式接口:Iterable``Iterator``Iterable

Iterator<String> sourceIterator = Arrays.asList("A", "B", "C").iterator();

Iterable<String> iterable = () -> sourceIterator;
Stream<String> targetStream = StreamSupport.stream(iterable.spliterator(), false);
2022-03-08