Given an Iterator, the task is to convert it into Iterables 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:
- By overriding the abstract method Iterable.iterator():
- Get the Iterator.
- Override the Iterable.iterator() method and get the iterable.
- Return the Iterable.
Below is the implementation of the above approach:
import java.util.*;
class GFG {
public static <T> Iterable<T>
getIterableFromIterator(Iterator<T> iterator)
{
return new Iterable<T>() {
@Override
public Iterator<T> iterator()
{
return iterator;
}
};
}
public static void main(String[] args)
{
Iterator<Integer>
iterator = Arrays.asList(1, 2, 3, 4, 5)
.iterator();
Iterable<Integer>
iterable = getIterableFromIterator(iterator);
iterable.forEach(System.out::println);
}
}
|
- Using Java 8 lambda expression:
- Get the Iterator.
- Convert the iterator to iterable using Lambda Expression.
- Return the Iterable.
Below is the implementation of the above approach:
import java.util.*;
class GFG {
public static <T> Iterable<T>
getIterableFromIterator(Iterator<T> iterator)
{
return () -> iterator;
}
public static void main(String[] args)
{
Iterator<Integer>
iterator = Arrays.asList(1, 2, 3, 4, 5)
.iterator();
Iterable<Integer>
iterable = getIterableFromIterator(iterator);
iterable.forEach(System.out::println);
}
}
|
- Using Spliterators:
- Get the Iterator.
- Convert the iterator to Spliterator using Spliterators.spliteratorUnknownSize() method.
- Convert the Spliterator into Sequential Stream using StreamSupport.stream() method.
- Collect the elements of the Sequential Stream as an Iterable using collect() method.
- Return the Iterable.
Below is the implementation of the above approach:
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
class GFG {
public static <T> Iterable<T>
getIterableFromIterator(Iterator<T> iterator)
{
return StreamSupport
.stream(Spliterators.spliteratorUnknownSize(iterator, 0),
false)
.collect(Collectors.toList());
}
public static void main(String[] args)
{
Iterator<Integer>
iterator = Arrays.asList(1, 2, 3, 4, 5)
.iterator();
Iterable<Integer>
iterable = getIterableFromIterator(iterator);
iterable.forEach(System.out::println);
}
}
|
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!