Sequenced Collection Reversed Views
Use reversed(), getFirst, and getLast from the JDK 21 SequencedCollection interfaces so order-sensitive access no longer needs size-minus-one index arithmetic.
Code
import java.util.LinkedHashMap;
import java.util.List;
import java.util.SequencedCollection;
import java.util.SequencedMap;
public class SequencedAccess {
public static void main(String[] args) {
List<String> steps = List.of("parse", "validate", "execute", "report");
// JDK 21 前只能写 steps.get(steps.size() - 1);现在两端有专用方法
System.out.println("first: " + steps.getFirst() + " last: " + steps.getLast());
// reversed() 返回原集合的活 view:后续修改会实时反映,不是一次性拷贝
SequencedCollection<String> reversed = steps.reversed();
System.out.println("reversed: " + reversed);
LinkedHashMap<String, String> timeline = new LinkedHashMap<>();
timeline.put("09:00", "build passed");
timeline.put("09:05", "deployed");
SequencedMap<String, String> view = timeline;
System.out.println("first entry: " + view.firstEntry());
System.out.println("last entry: " + view.lastEntry());
// putFirst 把迟到的事件插回开头;reversed().keySet() 得到倒序键导出
timeline.putFirst("08:55", "queued");
System.out.println("newest first: " + timeline.reversed().keySet());
}
}How it works
Sequenced Collection Reversed Views comes down to the class SequencedAccess and the function main.
What to watch for
- No external packages — everything relies on the language’s built-in APIs.
Using it
Signature: public static void main(String[] args)
Running the file prints labeled results such as first:, reversed:, first entry: — each operation’s effect is visible in the output.
Key statements
List<String> steps = List.of("parse", "validate", "execute", "report");
LinkedHashMap<String, String> timeline = new LinkedHashMap<>();
SequencedCollection<String> reversed = steps.reversed();
Interactive Tools for This Topic
FAQ
- What does Sequenced Collection Reversed Views print when run?
- Invoke the file as-is — the `first:`, `reversed:`, `first entry:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.