Skip to content

Instantly share code, notes, and snippets.

@KevinTCoughlin
Last active November 19, 2015 01:18
Show Gist options
  • Save KevinTCoughlin/97465cd83e2a5eb53114 to your computer and use it in GitHub Desktop.
Save KevinTCoughlin/97465cd83e2a5eb53114 to your computer and use it in GitHub Desktop.
Iterator implementation using composition that allows you to peek at the next value.
public class PeekIterator<T> {
@NonNull private final Iterator<T> iterator;
@Nullable private final T current;
public PeekIterator(Iterator<T> iter) {
this.iterator = iter;
}
public boolean hasNext() {
if (current != null) {
return true;
}
return this.iterator.hasNext();
}
public T next() {
if (current != null) {
final T curr = current;
current = null;
return curr;
}
return this.iterator.next();
}
public T peek() {
if (current == null) {
current = this.next();
}
return current;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment