To iterate over a list in Java in reverse order, you can use the listIterator()
method or a reverse for loop.
In this example,
numbers
with integer elements.listIterator()
method.hasPrevious()
and previous()
methods of the list iterator to iterate over the list in reverse order.// Iterate over list in reverse using ListIterator
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>(List.of(1, 2, 3, 4, 5));
ListIterator<Integer> iterator = numbers.listIterator(numbers.size());
while (iterator.hasPrevious()) {
System.out.println(iterator.previous());
}
}
}
5 4 3 2 1
In this example,
names
with string elements.// Iterate over list in reverse using reverse loop
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>(List.of("Alice", "Bob", "Charlie", "David"));
Collections.reverse(names);
for (String name : names) {
System.out.println(name);
}
}
}
David Charlie Bob Alice
In this tutorial, we learned How to Iterate Over a List in Reverse Order in Java language with well detailed examples.