Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Iterator

An object that hands out collection elements one by one.

Available since: Java 1.2

Syntax

public interface Iterator<E> {
    boolean hasNext();
    E next();
    default void remove();
}

Examples

Manual iteration:

void main() {
    Iterator<String> it = List.of("a", "b", "c").iterator();
    while (it.hasNext()) {
        IO.println(it.next());
    }
}

Output:

a
b
c

Safe removal during iteration:

void main() {
    List<Integer> nums = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6));
    Iterator<Integer> it = nums.iterator();
    while (it.hasNext()) {
        if (it.next() % 2 == 0) {
            it.remove();
        }
    }
    IO.println(nums);
}

Output:

[1, 3, 5]

Notes

next() past the end throws NoSuchElementException, so check hasNext() first. it.remove() removes the last returned element — the only safe way to remove while iterating. Today removeIf() is shorter for this task.

See also

  • Iterable — The interface of everything that a for-each loop can iterate over.
  • Collection.removeIf() — Removes all collection elements that match a condition.

Related recipes

In the tutorial

  • Iterating over collections — How to go through a collection in Java: the for-each loop, indexes, forEach with a lambda, iterating a map, Iterator and removeIf.

Thanks for reading!

Donate to the site — we work hard for you.