Why was the PeekingIterator in the Guava library not mentioned ?

  • 0

    Here's the PeekingIterator implementation in the Guava library (developed by Google).

    The key difference with most of other Java solutions posted here is that this version is null safe. It's perfectly OK to have a null element in PeekingIterator and hasNext() will return true in Guava. But other solutions will return false if it simply checks whether the cached value is null.

    One thing worth mentioning is that the Guava implementation isn't thread-safe.

    private static class PeekingImpl<E> implements PeekingIterator<E> {
        private final Iterator<? extends E> iterator;
        private boolean hasPeeked;
        private E peekedElement;
        public PeekingImpl(Iterator<? extends E> iterator) {
            this.iterator = (Iterator)Preconditions.checkNotNull(iterator);
        public boolean hasNext() {
            return this.hasPeeked || this.iterator.hasNext();
        public E next() {
            if(!this.hasPeeked) {
                return this.iterator.next();
            } else {
                Object result = this.peekedElement;
                this.hasPeeked = false;
                this.peekedElement = null;
                return result;
        public E peek() {
            if(!this.hasPeeked) {
                this.peekedElement = this.iterator.next();
                this.hasPeeked = true;
            return this.peekedElement;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.