假设以下是具有整数值的迭代器-
Iterator<Integer> iterator = Arrays.asList(50, 100, 200, 300, 400, 500, 1000).iterator();
现在,将此迭代器转换为列表-
List<Integer> myList = new ArrayList<>(); iterator.forEachRemaining(myList::add);
以下是在Java中将Iterator转换为List的程序-
import java.util.*; public class Demo { public static void main(String[] args){ Iterator<Integer> iterator = Arrays.asList(50, 100, 200, 300, 400, 500, 1000).iterator(); List<Integer> myList = new ArrayList<>(); iterator.forEachRemaining(myList::add); System.out.println("Iterator to list = "+myList); } }
输出结果
Iterator to list = [50, 100, 200, 300, 400, 500, 1000]