假设以下是具有整数值的迭代器-
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