Skip to content

Instantly share code, notes, and snippets.

@ibalashov
Created May 7, 2018 15:47
Show Gist options
  • Save ibalashov/9d04ac19b97c0e9b8485e90a6bb10bf2 to your computer and use it in GitHub Desktop.
Save ibalashov/9d04ac19b97c0e9b8485e90a6bb10bf2 to your computer and use it in GitHub Desktop.
package com.outbrain.utils;
import java.util.Iterator;
public class InterleavedIterator<T> implements Iterator<T> {
private Iterator<T> it1;
private Iterator<T> it2;
private boolean takeFirst;
public InterleavedIterator(Iterator<T> it1, Iterator<T> it2) {
this(it1, it2, true);
}
public InterleavedIterator(Iterator<T> it1, Iterator<T> it2, final boolean takeFirst) {
this.it1 = it1;
this.it2 = it2;
this.takeFirst = takeFirst;
}
@Override
public boolean hasNext() {
return it1.hasNext() || it2.hasNext();
}
@Override
public T next() {
T res = null;
if (takeFirst && it1.hasNext()) {
res = it1.next();
takeFirst = false;
} else if (it2.hasNext()) {
res = it2.next();
takeFirst = true;
} else if (it1.hasNext()) {
res = it1.next();
}
return res;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment