在 Java 中将 Iterator 转换为 Iterable
java 8object oriented programmingprogramming
假设以下是带有整数值 − 的 Iterator
Iterator<Integer>iterator = Arrays.asList(20, 40, 60, 80, 100, 120, 150, 200).iterator();
现在,将 Iterator 转换为 Iterable −
Iterable<Integer>iterable = StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, 0),false).collect(Collectors.toList());
示例
以下是在 Java 中将 Iterator 转换为 Iterable 的程序 −
import java.util.*; import java.util.stream.Collectors; import java.util.stream.StreamSupport; public class Demo { public static void main(String[] args) { Iterator<Integer>iterator = Arrays.asList(20, 40, 60, 80, 100, 120, 150, 200).iterator(); Iterable<Integer>iterable = StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, 0), false).collect(Collectors.toList()); System.out.println("Iterable = "); iterable.forEach(System.out::println); } }
输出
Iterable = 20 40 60 80 100 120 150 200