Command Palette

Search for a command to run...

Back to the lesson: Topic 9.12 — Sequenced Collections
Core Java · Example 2 of 2 Java 21+

reversed() is a live view

Java 21 added SequencedCollection, SequencedSet and SequencedMap: one standard way to get the first and last element, add at either end, and walk in reverse with reversed(), for every collection that has a defined order.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Using sequenced methods, write code that rotates a list one step to the left (first element moves to the end).

02

Print the three most recently inserted keys of a LinkedHashMap, newest first.

Explain it without notes

01

What problem do sequenced collections solve, and which Java version added them?

02

Why does TreeSet.addFirst throw, while LinkedHashSet.addFirst works?

03

Is list.reversed() a copy or a view? What are the consequences?

reversed() is a live view Java 21+
This example needs Java 21+. The in-browser compiler is Java 17: install JDK 21 or newer and run it with "java Main.java".

Expected output

back sees the change: [4, 3, 2, 1]
nums: [1, 2, 3, 40]
TreeSet reversed: [5, 3, 1], first=1