Created
July 27, 2011 14:47
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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