-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathreverse-list-iteration.yaml
More file actions
50 lines (50 loc) · 1.67 KB
/
reverse-list-iteration.yaml
File metadata and controls
50 lines (50 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
---
id: 96
slug: "reverse-list-iteration"
title: "Reverse list iteration"
category: "collections"
difficulty: "beginner"
jdkVersion: "21"
oldLabel: "Java 8"
modernLabel: "Java 21+"
oldApproach: "Manual ListIterator"
modernApproach: "reversed()"
oldCode: |-
for (ListIterator<String> it =
list.listIterator(list.size());
it.hasPrevious(); ) {
String element = it.previous();
System.out.println(element);
}
modernCode: |-
for (String element : list.reversed()) {
IO.println(element);
}
summary: "Iterate over a list in reverse order with a clean for-each loop."
explanation: "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."
whyModernWins:
- icon: "📖"
title: "Natural syntax"
desc: "Enhanced for loop instead of verbose ListIterator."
- icon: "⚡"
title: "No copying"
desc: "reversed() returns a view — no performance overhead."
- icon: "🧩"
title: "Consistent API"
desc: "Works on List, Deque, SortedSet uniformly."
support:
state: "available"
description: "Widely available since JDK 21 LTS (Sept 2023)"
prev: "collections/stream-toarray-typed"
next: "collections/unmodifiable-collectors"
related:
- "collections/sequenced-collections"
- "collections/immutable-list-creation"
- "streams/stream-tolist"
docs:
- title: "SequencedCollection (Java 21)"
href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/SequencedCollection.html"
- title: "JEP 431: Sequenced Collections"
href: "https://openjdk.org/jeps/431"