假设以下是具有整数值的迭代器-Iterator iterator = Arrays.asList(20, 40, 60, 80, 100, 120, 150, 200).iterator();
现在,将Iterator转换为Iterable-Iterable 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 iterator = Arrays.asList(20, 40, 60, 80, 100, 120, 150, 200).iterator();
Iterable 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