Skip to content

Instantly share code, notes, and snippets.

@davidsheldon
Created July 27, 2011 14:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidsheldon/1109506 to your computer and use it in GitHub Desktop.
Save davidsheldon/1109506 to your computer and use it in GitHub Desktop.
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