Convert an Iterator to a List in Java

Given an Iterator, the task is to convert it into List in Java.
Examples:
Input: Iterator = {1, 2, 3, 4, 5}
Output: {1, 2, 3, 4, 5}
Input: Iterator = {'G', 'e', 'e', 'k', 's'}
Output: {'G', 'e', 'e', 'k', 's'}
Below are the various ways to do so:
- Naive Approach:
- Get the Iterator.
- Create an empty list.
- Add each element of the iterator to the list using forEachRemaining() method.
- Return the list.
Below is the implementation of the above approach:
// Java program to get a List// from a given Iteratorimportjava.util.*;classGFG {// Function to get the Listpublicstatic<T> List<T>getListFromIterator(Iterator<T> iterator){// Create an empty listList<T> list =newArrayList<>();// Add each element of iterator to the Listiterator.forEachRemaining(list::add);// Return the Listreturnlist;}// Driver codepublicstaticvoidmain(String[] args){// Get the IteratorIterator<Integer>iterator = Arrays.asList(1,2,3,4,5).iterator();// Get the List from the IteratorList<Integer>list = getListFromIterator(iterator);// Print the listSystem.out.println(list);}}Output:[1, 2, 3, 4, 5]
- Using Iterable as intermediate:
- Get the Iterator.
- Convert the iterator to iterable using lambda expression.
- Convert the iterable to list using Stream.
- Return the list.
Below is the implementation of the above approach:
// Java program to get a List// from a given Iteratorimportjava.util.*;importjava.util.stream.Collectors;importjava.util.stream.StreamSupport;classGFG {// Function to get the Listpublicstatic<T> List<T>getListFromIterator(Iterator<T> iterator){// Convert iterator to iterableIterable<T> iterable = () -> iterator;// Create a List from the IterableList<T> list = StreamSupport.stream(iterable.spliterator(),false).collect(Collectors.toList());// Return the Listreturnlist;}// Driver codepublicstaticvoidmain(String[] args){// Get the IteratorIterator<Integer>iterator = Arrays.asList(1,2,3,4,5).iterator();// Get the List from the IteratorList<Integer>list = getListFromIterator(iterator);// Print the listSystem.out.println(list);}}Output:[1, 2, 3, 4, 5]



