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 IteratorÂÂimportjava.util.*;ÂÂclassGFG {   Â// Function to get the List   Âpublicstatic<T> List<T>   ÂgetListFromIterator(Iterator<T> iterator)   Â{       Â// Create an empty list       ÂList<T> list =newArrayList<>();       Â// Add each element of iterator to the List       Âiterator.forEachRemaining(list::add);       Â// Return the List       Âreturnlist;   Â}   Â// Driver code   Âpublicstaticvoidmain(String[] args)   Â{       Â// Get the Iterator       ÂIterator<Integer>           Âiterator = Arrays.asList(1,2,3,4,5)                          Â.iterator();       Â// Get the List from the Iterator       ÂList<Integer>           Âlist = getListFromIterator(iterator);       Â// Print the list       ÂSystem.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 IteratorÂÂimportjava.util.*;importjava.util.stream.Collectors;importjava.util.stream.StreamSupport;ÂÂclassGFG {   Â// Function to get the List   Âpublicstatic<T> List<T>   ÂgetListFromIterator(Iterator<T> iterator)   Â{       Â// Convert iterator to iterable       ÂIterable<T> iterable = () -> iterator;       Â// Create a List from the Iterable       ÂList<T> list = StreamSupport                          Â.stream(iterable.spliterator(),false)                          Â.collect(Collectors.toList());       Â// Return the List       Âreturnlist;   Â}   Â// Driver code   Âpublicstaticvoidmain(String[] args)   Â{       Â// Get the Iterator       ÂIterator<Integer>           Âiterator = Arrays.asList(1,2,3,4,5)                          Â.iterator();       Â// Get the List from the Iterator       ÂList<Integer>           Âlist = getListFromIterator(iterator);       Â// Print the list       ÂSystem.out.println(list);   Â}}Output:[1, 2, 3, 4, 5]
