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
Â
Âimport
java.util.*;
Â
Âclass
GFG {
Â
ÂÂ Â Â Â
// Function to get the List
   Â
public
static
<T> List<T>
   Â
getListFromIterator(Iterator<T> iterator)
   Â
{
Â
ÂÂ Â Â Â Â Â Â Â
// Create an empty list
       Â
List<T> list =
new
ArrayList<>();
Â
ÂÂ Â Â Â Â Â Â Â
// Add each element of iterator to the List
       Â
iterator.forEachRemaining(list::add);
Â
ÂÂ Â Â Â Â Â Â Â
// Return the List
       Â
return
list;
   Â
}
Â
ÂÂ Â Â Â
// Driver code
   Â
public
static
void
main(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
Â
Âimport
java.util.*;
import
java.util.stream.Collectors;
import
java.util.stream.StreamSupport;
Â
Âclass
GFG {
Â
ÂÂ Â Â Â
// Function to get the List
   Â
public
static
<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
       Â
return
list;
   Â
}
Â
ÂÂ Â Â Â
// Driver code
   Â
public
static
void
main(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]