将迭代器转换为列表会产生一个空列表

Converting an iterator to a list results in an empty list

我有等同于,来自 here:

Iterator<String> sourceIterator = Arrays.asList("A", "B", "C").iterator();
sourceIterator.forEachRemaining(source -> System.out.println(source)); // prints out all elements
Iterable<String> iterable = () -> sourceIterator;
List<String> targetList = StreamSupport.stream(iterable.spliterator(), false).
    .collect(Collectors.toList());
System.out.println(targetList.isEmpty()) // prints true

在我想出进行转换的方法之前,我已经添加了一些调试打印语句来帮助我。但事实证明流是空的。所以我想知道我的内容或方法是否不太正确?

阅读 forEachRemaining 它说:

Performs the given action for each remaining element until all elements have been processed or the action throws an exception. Actions are performed in the order of iteration, if that order is specified. Exceptions thrown by the action are relayed to the caller.

它看起来不像是从迭代器中删除任何东西,所以我不认为是那样。

使用代码,看起来 forEachRemaining 确实清空了流。没有那条线,流不会以空结束。问题中 iterator 的链接解释给出了这个默认实现:

while (hasNext())
    action.accept(next());

这将清空迭代器。这与 spliterator 不同:

invokes tryAdvance(java.util.function.Consumer<? super T>)

不是next(),但无论如何,你不能迭代两次。