Reverse list iteration
Iterate over a list in reverse order with a clean for-each loop.
Porównanie kodu
✕ Java 8
for (ListIterator<String> it =
list.listIterator(list.size());
it.hasPrevious(); ) {
String element = it.previous();
System.out.println(element);
}
✓ Java 21+
for (String element : list.reversed()) {
IO.println(element);
}
Widzisz problem z tym kodem? Daj nam znać.
Dlaczego nowoczesne podejście wygrywa
Natural syntax
Enhanced for loop instead of verbose ListIterator.
No copying
reversed() returns a view — no performance overhead.
Consistent API
Works on List, Deque, SortedSet uniformly.
Stare podejście
Manual ListIterator
Nowoczesne podejście
reversed()
Od JDK
21
Poziom trudności
Początkujący
Wsparcie JDK
Reverse list iteration
Dostępne
Widely available since JDK 21 LTS (Sept 2023)
Jak to działa
The reversed() method from SequencedCollection returns a reverse-ordered view of the list. This view is backed by the original list, so no copying occurs. The enhanced for loop syntax makes reverse iteration as readable as forward iteration.
Powiązana dokumentacja