Sobes.tech
Senior

What other methods does Iterator have besides hasNext, next, and remove?

sobes.tech AI

Answer from AI

In Java, the Iterator interface from the standard library (java.util.Iterator) defines three main methods:

  • hasNext() — checks if there is a next element.
  • next() — returns the next element.
  • remove() — removes the last returned element from the collection.

Additionally, starting from Java 8, the Iterator interface is extended with the method:

  • forEachRemaining(Consumer<? super E> action) — performs the given action for each remaining element of the iterator, which is convenient for processing elements without an explicit loop.

Example of using forEachRemaining:

Iterator<String> it = list.iterator();
it.forEachRemaining(System.out::println);

There are no other methods in the standard Iterator, but some extensions and specialized iterators may have additional methods.