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?
-
4Ummm, because it doesn't. That seems like an impossible question to answer satisfactorily.– Elliott FrischCommented Aug 30, 2018 at 23:55
-
1Guava has a peeking iterator, if it helps.– shmoselCommented 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.– La-comadrejaCommented 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/…– Adrian SmithCommented Jul 29, 2021 at 14:37
3 Answers
Why doesn't the standard Java iterator have peek()?
Because
peek()
is not part of the Iterator design pattern as it is normally described.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.
Because the
peek()
method has potential impacts on the semantics for iterators of lazy data sources.Because implementing
peek()
affects the efficiency (memory, CPU) of a iterator in some circumstances. Whether you actually use it or not.Because
peek()
would in some obscure circumstances lead to a memory leak.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.
-
-
-
1It could never be atomic by design. You need
hasNext()
to kind of fix the availability of the next element. Commented Sep 14, 2020 at 2:31 -
1To 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.gif (it.hasNext()) e = it.next();
is not atomic ifit
is shared by more than one thread. I reckon this renders the atomicity ofpeek
to be moot. Commented Sep 14, 2020 at 3:34
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.
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;
}
}
-
1
hasNext
has a bug. It should beiterator.hasNext () || peeked
, sincepeek
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 PCommented 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; } } Commented Nov 7, 2022 at 20:02