7
如何将迭代器转换为流?
我正在寻找一种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 …