Given an iterator of iterators, return all of the elements from the iterators in order. Looking for code review, optimizations, and best practices. Verifying complexity to be \$O(n)\$, where \$n\$ is the total number of elements from all iterators.
public class IteratorOfIterator implements Iterator<Integer>{
private final Iterator<Iterator<Integer>> iteratorOfIterator;
private Iterator<Integer> currentIterator;
public IteratorOfIterator(Iterator<Iterator<Integer>> iterator) {
this.iteratorOfIterator = iterator;
}
@Override
public boolean hasNext() {
while (currentIterator == null || !currentIterator.hasNext()) {
if (!iteratorOfIterator.hasNext()) return false;
currentIterator = iteratorOfIterator.next();
}
return true;
}
@Override
public Integer next() {
if (!hasNext()) {
throw new NoSuchElementException("the stuff cannot be null.");
}
return currentIterator.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException("The remove operation is not supported.");
}
}
public class IteratorOfIteratorTest {
@Test
public void testIterator() {
List<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
List<Integer> list2 = new ArrayList<>(Arrays.asList(5, 6, 7, 8));
List<Iterator<Integer>> combined = new ArrayList<>(Arrays.asList(list1.iterator(), null, list2.iterator()));
IteratorOfIterator ioi = new IteratorOfIterator(combined.iterator());
int[] expected = {1, 2, 3, 4, 5, 6, 7, 8};
int[] actual = new int[8];
int i = 0;
while (ioi.hasNext()) {
actual[i] = ioi.next();
i++;
}
assertArrayEquals(expected, actual);
}
}
Iterators.concat
from Guava \$\endgroup\$