In this post you can see two implementations, the only (minor) difference is that instead of iterators, an iterator of collection iterators is required.
This difference, combined with the requirement of looping through elements (a requirement that was not requested by the OP in this question) adds the overhead of copying iterators to the list.
The first approach is lazy: it will iterate over the element only when requesting this element, the "price" we have to pay is that the code is more complicated because it needs to handle more edge cases:
import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; public class MultiIterator<E> implements Iterator { List<Iterator<E>> iterators = new LinkedList<>(); Iterator<E> current = null; public MultiIterator(Iterator<Iterator<E>> iterator) {
and the second ("greedy" copying of all elements from all iterators in the requested order to the list and returning the iterator to this list):
import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class MultiIterator<E> { Iterator<Iterator<E>> iterator = null; List<E> elements = new LinkedList<>(); private MultiIterator(Iterator<Iterator<E>> iterator) { this.iterator = iterator; } private void copyElementsInOrder() { List<Iterator<E>> iterators = new LinkedList<>();
I included a simple βtestβ code to show how to use MultiIterator, this is not always trivial (due to the use of Generics), as you can see on the line:
Iterator<Integer> it = MultiIterator.<Integer>iterator(iterators.iterator());
alfasin
source share