Java : Iterator with Examples

Iterator (Java SE 21 & JDK 21) with Examples.
You will find code examples on most Iterator<E> methods.


Summary

An iterator over a collection. Iterator takes the place of Enumeration in the Java Collections Framework.

Class diagram

final var list = List.of("aaa", "bbb", "ccc");
System.out.println(list); // [aaa, bbb, ccc]

final var iterator = list.iterator();

System.out.println("-- next --");
while (iterator.hasNext()) {
    final var value = iterator.next();
    System.out.println(value);
}

// Result
// ↓
//-- next --
//aaa
//bbb
//ccc

Methods

default void forEachRemaining (Consumer<? super E> action)

Performs the given action for each remaining element until all elements have been processed or the action throws an exception.

final var list = List.of("aaa", "bbb", "ccc");
System.out.println(list); // [aaa, bbb, ccc]

final var iterator = list.iterator();

System.out.println("-- forEachRemaining --");
iterator.forEachRemaining(value -> {
    System.out.println(value);
});

// Result
// ↓
//-- forEachRemaining --
//aaa
//bbb
//ccc

boolean hasNext ()

Returns true if the iteration has more elements.

final var list = List.of("aaa", "bbb", "ccc");
System.out.println(list); // [aaa, bbb, ccc]

final var iterator = list.iterator();

System.out.println("-- next --");
while (iterator.hasNext()) {
    final var value = iterator.next();
    System.out.println(value);
}

// Result
// ↓
//-- next --
//aaa
//bbb
//ccc

E next ()

Returns the next element in the iteration.

Please see hasNext().

default void remove ()

Removes from the underlying collection the last element returned by this iterator (optional operation).

final var list = new ArrayList<Integer>();
Collections.addAll(list, 1, 2, 3, 4, 5, 6);

System.out.println(list); // [1, 2, 3, 4, 5, 6]

final var iterator = list.iterator();
while (iterator.hasNext()) {
    final var value = iterator.next();
    if (value % 2 == 0) {
        iterator.remove();
    }
}

System.out.println(list); // [1, 3, 5]

Related posts

To top of page