14

Is there any particular reason the basic Java iterator was programmed not to have a function like peek(), which would return the next element without advancing the iterator?

4
  • 4
    Ummm, because it doesn't. That seems like an impossible question to answer satisfactorily. Commented Aug 30, 2018 at 23:55
  • 1
    Guava has a peeking iterator, if it helps.
    – shmosel
    Commented Aug 31, 2018 at 0:02
  • Thanks. I saw the peeking iterator and it's a bit surprising peek() is not in the standard Java iterator. Commented Aug 31, 2018 at 0:14
  • This is not an answer to the question as to "why", but for those who landed on this page looking for such an iterator, I can recommend guava.dev/releases/22.0/api/docs/com/google/common/collect/… Commented Jul 29, 2021 at 14:37

3 Answers 3

30

Why doesn't the standard Java iterator have peek()?

  1. Because peek() is not part of the Iterator design pattern as it is normally described.

  2. Because the vast majority of iterator use-cases don't require it. Forcing all implementations (including a myriad custom / 3rd party classes) to implement an unnecessary method would be a bad idea.

  3. Because the peek() method has potential impacts on the semantics for iterators of lazy data sources.

  4. Because implementing peek() affects the efficiency (memory, CPU) of a iterator in some circumstances. Whether you actually use it or not.

  5. Because peek() would in some obscure circumstances lead to a memory leak.

  6. Because ... KISS.

But ultimately, the real reason is ... because they designed it that way back in the year ~2000. And we weren't in the room when the design debates took place1.

1 - For what it is worth, it seems that most2 other languages have made the same decision for their standard iterator API. Rust seems to be an exception to this; see https://doc.rust-lang.org/std/iter/struct.Peekable.html.

2 - ... based on a highly non-scientific "survey" using Google search.


If you want an iterator abstraction that provides peek() as well, you can extend the Iterator interface and implement the iterators for yourself. Indeed an general purpose iterator-with-peek can easily be implemented as a wrapper for a regular Iterator.

Or look for a 3rd-party API / implementation(s); e.g. Guava, Apache Commons, etc.

4
  • 7. Because it wouldn't be atomic.
    – user207421
    Commented Sep 14, 2020 at 2:05
  • That is a property of an implementation of Iterator.
    – Stephen C
    Commented Sep 14, 2020 at 2:11
  • 1
    It could never be atomic by design. You need hasNext() to kind of fix the availability of the next element.
    – user207421
    Commented Sep 14, 2020 at 2:31
  • 1
    To the extent that that any kind of atomicity is meaningful ... it could be implemented. But this is in the context that the Iterator pattern is non-atomic by design; e.g if (it.hasNext()) e = it.next(); is not atomic if it is shared by more than one thread. I reckon this renders the atomicity of peek to be moot.
    – Stephen C
    Commented Sep 14, 2020 at 3:34
1

If you really need an iterator with peek(), why not use a LinkedList as your initial datastructure? It provides .peek() and .pop() to retrieve the head.

1

The following example implements an Iterator with a peek method. The implementation of remove is left for the reader.

import java.util.Iterator;

/**
 * An Iterator with a peek method for just one value.
 */
public class PeekIterator<T> implements Iterator<T>
{
  private Iterator<T> iterator;

  public PeekIterator (Iterator<T> iterator) { this.iterator = iterator; }

  private boolean peeked = false;
  private T peeked_value = null;

  public boolean hasNext () { return iterator.hasNext () || peeked; }

  public T next ()
  {
    T value;
    if (peeked) {
      peeked = false;
      value = peeked_value;
    }
    else
      if (iterator.hasNext ())
        value = iterator.next();
      else
        value = null;
    return value;
  }

  public T peek ()
  {
    T value;
    if (peeked)
      value = peeked_value;
    else {
      peeked = true;
      if (iterator.hasNext ())
        peeked_value = iterator.next ();
      else
        peeked_value = null;
      value = peeked_value;
    }
    return value;
  }
}
2
  • 1
    hasNext has a bug. It should be iterator.hasNext () || peeked, since peek could consume the last element on the underlying iterator. Then the iterator is empty, but on the PeekIterator, that peeked element still needs to be consumed.
    – Consti P
    Commented Mar 30, 2022 at 8:07
  • Its not enough to just add iterator.hasNext () || peeked, because now if you peek when there is no next element, peeked will still be true. If you run a hasNext() following a peek when you are at the end of the iterator, you will get a true response. The easy way to fix this is to add peek = false in the else statement when checking if hasNext is true: public T peek () { . . . if (iterator.hasNext ()) peeked_value = iterator.next (); else peeked_value = null; peeked =false value = peeked_value; } return value; } }
    – DanielWsk
    Commented Nov 7, 2022 at 20:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.