Java如何将迭代器转换为流?

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

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

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,但我没有发现任何东西。

回答:

一种方法是从迭代器创建一个拆分器,并将其用作流的基础:

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

Stream<String> targetStream = StreamSupport.stream(

Spliterators.spliteratorUnknownSize(sourceIterator, Spliterator.ORDERED),

false);

一个可能更易读的替代方法是使用Iterable-使用lambda从Iterator创建Iterable非常容易,因为Iterable是一个功能接口:

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

Iterable<String> iterable = () -> sourceIterator;

Stream<String> targetStream = StreamSupport.stream(iterable.spliterator(), false);

以上是 Java如何将迭代器转换为流? 的全部内容, 来源链接: utcz.com/qa/410816.html

回到顶部