首先,设置一个Interator-
Iterator<Integer>iterator = Arrays.asList(50, 100, 200, 400, 500, 1000).iterator();
现在,我们使用了流-
Stream<Integer>stream = convertIterator(iterator);
上面,方法convertIterator()用于转换。以下是方法-
public static <T> Stream<T> convertIterator(Iterator<T> iterator) { return StreamSupport.stream(((Iterable) () -> iterator).spliterator(), false); }
以下是在Java中将Iterator转换为Stream的程序-
import java.util.stream.*; import java.util.*; public class Demo { public static <T> Stream<T> convertIterator(Iterator<T> iterator) { return StreamSupport.stream(((Iterable) () -> iterator).spliterator(), false); } public static void main(String[] args) { Iterator<Integer>iterator = Arrays.asList(50, 100, 200, 400, 500, 1000).iterator(); Stream<Integer>stream = convertIterator(iterator); System.out.println("Iterator to Stream..."); stream.forEach(s -> System.out.println(s)); } }
输出结果
Iterator to Stream... 50 100 200 400 500 1000