SwadhyAI Notes

All Java notes

Java Iterator Methods Reference

›Short versionOpen if you only have a minute.
  • hasNext looks ahead and does not move. next moves forward and returns the element.
  • next on an exhausted iterator throws NoSuchElementException.
  • remove deletes the element most recently returned by next. Call it once per next.
  • remove before the first next, or twice after one next, throws IllegalStateException.
  • A for-each loop hides an iterator. collection.remove inside that loop is a structural change the iterator did not make.
  • ListIterator adds previous, set, and add. Those methods are not on Iterator.

Iterator provides a uniform way to walk through collection elements and safely remove the current element during traversal.

Methods

APIParametersReturnsBehaviorWatch for
hasNext()None.boolean.Reports whether another element can be read.Does not advance the iterator.
next()None.Next element.Advances cursor and returns current element.Throws NoSuchElementException if no next element exists.
remove()None.void.Removes the last element returned by next().Call once per next(); otherwise IllegalStateException.
forEachRemaining(Consumer action)Action to apply to remaining elements.void.Consumes all remaining elements in iteration order.Exceptions from action stop iteration.
ListIterator.add(E e)Element to insert.void.Inserts while traversing a List.Available on ListIterator, not plain Iterator.
ListIterator.previous()None.Previous element.Moves backward in lists.Requires a ListIterator from a List.

Which call fits

OptionBest forTradeoff
Enhanced forSimple read-only traversal.No direct safe remove call.
IteratorTraversal with safe removal.One-way and more verbose.
ListIteratorBidirectional List traversal and replacement/insertion.Only applies to List implementations.

Examples

Remove safely while iterating

java
Iterator<String> it = names.iterator();

while (it.hasNext()) {
    String name = it.next();
    if (name.isBlank()) {
        it.remove();
    }
}

Consume remaining elements

java
Iterator<Integer> it = scores.iterator();
if (it.hasNext()) {
    System.out.println("First: " + it.next());
}
it.forEachRemaining(System.out::println);

Iterator<String> it = names.iterator(); then it.remove() before any next(). What happens?

IllegalStateException. remove() deletes the last element returned by next(), and there is no such element yet. The legal order is next, then at most one remove, then another next if you need to delete again.