Skip to content

Instantly share code, notes, and snippets.

@ataylor284
Last active December 16, 2015 06:09
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 ataylor284/5389604 to your computer and use it in GitHub Desktop.
Save ataylor284/5389604 to your computer and use it in GitHub Desktop.
LookaheadIterator
import java.util.Iterator;
public class LookaheadIterator implements Iterator {
private Iterator iter;
private boolean hasLookahead;
private Object lookahead;
public LookaheadIterator(Iterator iter) {
this.iter = iter;
hasLookahead = false;
}
public boolean hasNext() {
return hasLookahead || iter.hasNext();
}
public Object next() {
if (hasLookahead) {
hasLookahead = false;
return lookahead;
} else {
return iter.next();
}
}
public void remove() {
throw new UnsupportedOperationException();
}
public Object peek() {
if (!hasLookahead) {
lookahead = iter.next();
hasLookahead = true;
}
return lookahead;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment