Java : Iterator with Examples
Iterator (Java SE 21 & JDK 21) with Examples.
You will find code examples on most Iterator<E> methods.
Summary
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)
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 ()
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 ()
Please see hasNext().
default void remove ()
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
- API Examples