Java : ListIterator with Examples
ListIterator (Java SE 21 & JDK 21) with Examples.
You will find code examples on most ListIterator<E> methods.
Summary
final var list = List.of("aaa", "bbb", "ccc");
System.out.println(list); // [aaa, bbb, ccc]
final var iterator = list.listIterator();
System.out.println("-- next --");
while (iterator.hasNext()) {
final var value = iterator.next();
System.out.println(value);
}
// Result
// ↓
//-- next --
//aaa
//bbb
//ccc
System.out.println("-- previous --");
while (iterator.hasPrevious()) {
final var value = iterator.previous();
System.out.println(value);
}
// Result
// ↓
//-- previous --
//ccc
//bbb
//aaa
Methods
void add (E e)
final var list = new ArrayList<String>();
Collections.addAll(list, "aaa", "bbb", "ccc");
System.out.println(list); // [aaa, bbb, ccc]
final var iterator = list.listIterator();
while (iterator.hasNext()) {
final var value = iterator.next();
iterator.add(value.toUpperCase());
}
System.out.println(list); // [aaa, AAA, bbb, BBB, ccc, CCC]
boolean hasNext ()
final var list = List.of("aaa", "bbb", "ccc");
System.out.println(list); // [aaa, bbb, ccc]
final var iterator = list.listIterator();
System.out.println("-- next --");
while (iterator.hasNext()) {
final var index = iterator.nextIndex();
final var value = iterator.next();
System.out.printf("index = %d, value = %s%n", index, value);
}
// Result
// ↓
//-- next --
//index = 0, value = aaa
//index = 1, value = bbb
//index = 2, value = ccc
boolean hasPrevious ()
final var list = List.of("aaa", "bbb", "ccc");
System.out.println(list); // [aaa, bbb, ccc]
final var iterator = list.listIterator(list.size());
System.out.println("-- previous --");
while (iterator.hasPrevious()) {
final var index = iterator.previousIndex();
final var value = iterator.previous();
System.out.printf("index = %d, value = %s%n", index, value);
}
// Result
// ↓
//-- previous --
//index = 2, value = ccc
//index = 1, value = bbb
//index = 0, value = aaa
E next ()
Please see hasNext().
int nextIndex ()
Please see hasNext().
E previous ()
Please see hasPrevious().
int previousIndex ()
Please see hasPrevious().
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.listIterator();
while (iterator.hasNext()) {
final var value = iterator.next();
if (value % 2 == 0) {
iterator.remove();
}
}
System.out.println(list); // [1, 3, 5]
void set (E e)
final var list = new ArrayList<String>();
Collections.addAll(list, "aaa", "bbb", "ccc");
System.out.println(list); // [aaa, bbb, ccc]
final var iterator = list.listIterator();
while (iterator.hasNext()) {
final var value = iterator.next();
iterator.set(value.toUpperCase());
}
System.out.println(list); // [AAA, BBB, CCC]
Methods declared in Iterator
Related posts
- API Examples