Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A class to interate through the cross product of all of the pairs of values from iterators.
import java.util.Iterator;
import com.google.common.collect.AbstractIterator;
import com.google.common.collect.Iterators;
/**
*/
public abstract class CrossProductIterator<A, B, C> extends AbstractIterator<A> {
private Iterator<B> outer_;
private B curOuter_;
private Iterator<C> inner_;
private final Iterable<C> suffixes_;
public CrossProductIterator(final Iterable<B> prefixes, final Iterable<C> suffixes) {
outer_ = prefixes.iterator();
inner_ = Iterators.emptyIterator();
suffixes_ = suffixes;
curOuter_ = null;
}
@Override
protected A computeNext() {
while (true) {
if (inner_.hasNext()) {
return combiner(curOuter_, inner_.next());
}
if (outer_.hasNext()) {
curOuter_ = outer_.next();
inner_ = suffixes_.iterator();
}
else {
return endOfData();
}
}
}
abstract A combiner(final B outer, final C inner);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.