Appearance
Lesson 04 · Sequenced Collections
Objectives
After this lesson you will be able to:
- Use the Java 21
SequencedCollection,SequencedSet, andSequencedMapinterfaces. - Access first/last elements and obtain a reversed view.
- Know which existing types gained these methods.
What Java 21 added (JEP 431)
Before Java 21 there was no common type for "a collection with a defined encounter order and both ends reachable." Java 21 adds three interfaces:
SequencedCollection<E>—addFirst/addLast,getFirst/getLast,removeFirst/removeLast, andreversed().SequencedSet<E>— aSequencedCollectionthat is also aSet.SequencedMap<K,V>—firstEntry/lastEntry,putFirst/putLast,pollFirstEntry/pollLastEntry,reversed(), plus sequencedkeySet/values/entrySet.
java
SequencedCollection<Integer> sc = new ArrayList<>(List.of(1, 2, 3));
sc.getFirst(); // 1 (was list.get(0))
sc.getLast(); // 3 (was list.get(list.size()-1))
sc.addFirst(0); // [0, 1, 2, 3]
sc.reversed(); // a reversed VIEW: [3, 2, 1, 0]Which types implement them
| Type | New super-interface |
|---|---|
List (e.g. ArrayList, LinkedList) | SequencedCollection |
Deque (e.g. ArrayDeque) | SequencedCollection |
LinkedHashSet | SequencedSet |
SortedSet/TreeSet | SequencedSet |
LinkedHashMap | SequencedMap |
SortedMap/TreeMap | SequencedMap |
Exam trap
reversed() returns a view backed by the original — changes write through, and iterating it costs nothing extra. A plain HashSet/HashMap is NOT sequenced (no defined order), so it has none of these methods. getFirst()/getLast() throw NoSuchElementException on an empty collection.
Beyond the exam
reversed() on a SequencedMap returns a SequencedMap whose encounter order is reversed; on a TreeMap that's the descending order — a cleaner alternative to descendingMap() for simple needs.
Key Takeaways
- Java 21's
SequencedCollection/SequencedSet/SequencedMapunify ordered access:getFirst/getLast,addFirst/addLast, andreversed(). List,Deque,LinkedHashSet,TreeSet,LinkedHashMap, andTreeMapimplement them;HashSet/HashMapdo not (unordered).reversed()is a live view, not a copy;getFirst/getLastthrowNoSuchElementExceptionwhen empty.
Lesson Quiz
Which method gives the first element of a List in Java 21?
Does HashSet implement SequencedSet?
What does reversed() return?
What does getFirst() do on an empty List?
Next: Comparison & Sorting. Run the matching code in labs/src/main/java/com/jse21/m05_collections/.