Is it possible to merge iterators in Java? I have two iterators and I want to combine/merge them so that I could iterate though their elements in one go (in same loop) rathe
The Merged Iterator:
import static java.util.Arrays.asList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;
public class ConcatIterator implements Iterator {
private final List> iterables;
private Iterator current;
@SafeVarargs
public ConcatIterator(final Iterable... iterables) {
this.iterables = new LinkedList<>(asList(iterables));
}
@Override
public boolean hasNext() {
checkNext();
return current != null && current.hasNext();
}
@Override
public T next() {
checkNext();
if (current == null || !current.hasNext()) throw new NoSuchElementException();
return current.next();
}
@Override
public void remove() {
if (current == null) throw new IllegalStateException();
current.remove();
}
private void checkNext() {
while ((current == null || !current.hasNext()) && !iterables.isEmpty()) {
current = iterables.remove(0).iterator();
}
}
}
The concat method to create an Iterable:
@SafeVarargs
public static Iterable concat(final Iterable... iterables) {
return () -> new ConcatIterator<>(iterables);
}
Simple JUnit test:
@Test
public void testConcat() throws Exception {
final Iterable it1 = asList(1, 2, 3);
final Iterable it2 = asList(4, 5);
int j = 1;
for (final int i : concat(it1, it2)) {
assertEquals(j, i);
j++;
}
}