Sequenced Collections (Java 21)
SequencedCollection, SequencedSet, SequencedMap interfaces and reverse views
- Use getFirst/getLast/addFirst/addLast on any sequenced collection
- Obtain a reversed view of a list or map without copying
- Identify which existing types implement the new interfaces
Complete Study Guide Chapter: New Interfaces in Java 21 Collection Hierarchy
Table of Contents
- Overview & Motivation
- The Existing Collection Hierarchy (Pre-Java 21)
- The New Collection Hierarchy (Java 21+)
- What Makes a Collection "Sequenced"? — The Three Conditions
- Applying the Conditions — Which Collections Qualify?
- Why Is SequencedSet Needed Separately?
- The Gap Being Filled — Why These Interfaces Exist
- SequencedCollection Interface — Methods & Usage
- SequencedSet Interface — Methods & Usage
- SequencedMap Interface — Methods & Usage
- UnsupportedOperationException — Sorted Types
- Interview Notes
- Common Mistakes
- Best Practices
- Practice Questions
- Summary
1. Overview & Motivation
What Was Added in Java 21?
Java 21 introduced three new interfaces into the Java Collections Framework:
| Interface | Package |
|---|---|
SequencedCollection | java.util |
SequencedSet | java.util |
SequencedMap | java.util |
These interfaces were not created from scratch — they were inserted into the existing hierarchy, slotting between existing interfaces and implementation classes.
The Core Problem They Solve
Before Java 21, certain collections had a well-defined order (insertion order, sorted order), and you could logically speak of a "first element" and a "last element." However:
- Each collection type had its own differently-named methods for accessing, adding, and removing first/last elements.
- There was no common interface that unified these operations.
- There was no standard way to get a reversed view of a collection.
This made code harder to write, harder to read, and harder to maintain.
2. The Existing Collection Hierarchy (Pre-Java 21)
In this pre-Java 21 world:
List,Deque,LinkedHashSet,TreeSet,LinkedHashMap,TreeMap— all have a defined order.- But there is no shared interface that groups them together and exposes common first/last operations.
3. The New Collection Hierarchy (Java 21+)
The three new interfaces slot into the hierarchy like this:
SequencedCollection, SequencedSet, and SequencedMap, plus the updated parent relationships of existing classes.Key structural changes:
| Before Java 21 | After Java 21 |
|---|---|
List extends Collection | List extends SequencedCollection |
Deque extends Queue | Deque extends SequencedCollection |
LinkedHashSet implements Set | LinkedHashSet implements SequencedSet |
SortedSet extends Set | SortedSet extends SequencedSet |
LinkedHashMap implements Map | LinkedHashMap implements SequencedMap |
SortedMap extends Map | SortedMap extends SequencedMap |
4. What Makes a Collection "Sequenced"? The Three Conditions
A collection can be considered "sequenced" (and thus eligible to extend/implement one of the new interfaces) if and only if it satisfies all three of the following conditions:
Condition 1: Predictable Iteration
The collection must maintain its elements in a consistent, well-defined order every time you iterate over it.
There are two acceptable orderings:
| Ordering Type | Description | Example Collections |
|---|---|---|
| Insertion Order | Elements appear in the order they were inserted | List, Deque, LinkedHashSet, LinkedHashMap |
| Sorted Order | Elements appear in sorted (ascending/descending) order | TreeSet (SortedSet), TreeMap (SortedMap) |
[1, 5, 14] for those three values is equally predictable — the behavior is consistent and repeatable, not random.Collections that fail Condition 1:
HashSet— iteration order is undefined, based on hash codesHashMap— no order guaranteeHashtable— no order guaranteePriorityQueue— only guarantees the head element is min/max; rest of iteration is heap-order (not consistent)
Condition 2: Access and Manipulation of First and Last Elements
The collection must support reading, adding, and removing elements at both ends — the first position and the last position.
"Support" here means it is architecturally possible given the underlying data structure, even if the exact API method names differ across types.
| Operation | Description |
|---|---|
| Access first | Read the element at the front without removing it |
| Access last | Read the element at the end without removing it |
| Add first | Insert an element at the front |
| Add last | Insert an element at the end |
| Remove first | Remove and return the element at the front |
| Remove last | Remove and return the element at the end |
Collections that fail Condition 2:
Queue— supports insertion only at the tail, removal only at the head; you cannot access or remove the last element, and cannot add at the front.
Condition 3: Reversible View
The collection must support obtaining a reversed view — a view of the same underlying collection that presents elements in reverse order.
Collections that fail Condition 3:
- Any collection that fails Condition 1 or 2 also effectively fails this, because reversing an unordered collection is meaningless.
Queue— no reverse iteration supported.
Decision Flowchart
5. Applying the Conditions Which Collections Qualify?
Full Eligibility Table
| Collection | Condition 1:\nPredictable Order | Condition 2:\nFirst/Last Ops | Condition 3:\nReversible View | Result |
|---|---|---|---|---|
List (ArrayList, LinkedList) | ✅ Insertion order | ✅ Yes (get/add/remove by index) | ✅ Collections.reverse() | ✅ Under SequencedCollection |
Deque (ArrayDeque, LinkedList) | ✅ Insertion order | ✅ getFirst/getLast/addFirst/addLast | ✅ reverse() | ✅ Under SequencedCollection |
Queue | ✅ Insertion order | ❌ No last access/add | ❌ Not supported | ❌ Excluded |
PriorityQueue | ❌ No consistent order | ❌ N/A | ❌ N/A | ❌ Excluded |
HashSet | ❌ No order | ❌ N/A | ❌ N/A | ❌ Excluded |
LinkedHashSet | ✅ Insertion order (doubly linked list) | ✅ Possible (doubly linked list) | ✅ Possible (reverse iteration) | ✅ Under SequencedSet |
TreeSet (SortedSet) | ✅ Sorted order | ✅ first()/last()/add/remove | ✅ descendingIterator() | ✅ Under SequencedSet |
HashMap | ❌ No order | ❌ N/A | ❌ N/A | ❌ Excluded |
Hashtable | ❌ No order | ❌ N/A | ❌ N/A | ❌ Excluded |
LinkedHashMap | ✅ Insertion order (doubly linked list) | ✅ Possible | ✅ Possible | ✅ Under SequencedMap |
TreeMap (SortedMap) | ✅ Sorted order | ✅ firstKey/lastKey/put/remove | ✅ descendingMap() | ✅ Under SequencedMap |
Deep Dive: Why Queue Is Excluded
1Queue — FIFO structure2─────────────────────3Insert → [tail] ────── [head] → Remove (peek/poll)4
5❌ Cannot access the last element6❌ Cannot add at the front7❌ Cannot remove from the back8❌ No reverse viewQueue is fundamentally a one-directional structure. Even though it maintains insertion order (Condition 1), it fails Conditions 2 and 3.
Deep Dive: Why PriorityQueue Is Excluded
1PriorityQueue — Heap-based2───────────────────────────3Internally: [heap structure]4Only guarantees: head = min (or max)5Rest of iteration: undefined order6
7❌ Fails Condition 1 (unpredictable iteration beyond the head)8❌ Conditions 2 and 3 not applicableA PriorityQueue does not maintain any consistent end-to-end order. Only the top (head) element is guaranteed to be the minimum/maximum. Everything else is heap-internal ordering, which is not predictable to the caller.
Deep Dive: Why LinkedHashSet Qualifies (Yellow in Lecture)
LinkedHashSet internally uses a doubly linked list (in addition to a hash table) to maintain insertion order.
Because of the doubly linked list:
- You can traverse from the front (first inserted) to the back (last inserted) ✅
- You can traverse in reverse (from last to first) ✅
- You can add a node at the head or tail of the linked list ✅
- You can remove a node from head or tail ✅
LinkedHashSet did not expose public addFirst(), getLast() etc. methods. The lecture marks these as "yellow" — meaning the underlying data structure can support these operations, and Java 21 extends the API to expose them properly via the SequencedSet interface.6. Why Is SequencedSet Needed Separately?
This is the third key question from the lecture.
The Distinction: Duplicates vs. No Duplicates
| Interface | Duplicates Allowed? | Example Implementations |
|---|---|---|
SequencedCollection | ✅ Yes | List, Deque |
SequencedSet | ❌ No | LinkedHashSet, TreeSet |
SequencedSet extends SequencedCollection and Set. The Set contract enforces uniqueness. Because LinkedHashSet and TreeSet do not allow duplicates, they cannot simply implement SequencedCollection — they must implement the more specific SequencedSet which carries the no-duplicate guarantee from Set.
LinkedHashSet extended SequencedCollection directly, it would inherit an interface that permits duplicates — which violates LinkedHashSet's contract. Hence the need for a separate SequencedSet.7. The Gap Being Filled Why These Interfaces Exist
The Pre-Java 21 Problem: Inconsistent APIs
Here is the pre-Java 21 way to perform equivalent first/last operations across different collection types:
| Operation | List | Deque | LinkedHashSet | SortedSet (TreeSet) |
|---|---|---|---|---|
| Get first | list.get(0) | deque.getFirst() | Manual iteration | sortedSet.first() |
| Get last | list.get(list.size()-1) | deque.getLast() | Manual iteration | sortedSet.last() |
| Add first | list.add(0, elem) | deque.addFirst(elem) | Not available | Not meaningful |
| Add last | list.add(elem) | deque.addLast(elem) | set.add(elem) | set.add(elem) |
| Remove first | list.remove(0) | deque.removeFirst() | Manual iteration | sortedSet.remove(first()) |
| Remove last | list.remove(list.size()-1) | deque.removeLast() | Manual iteration | sortedSet.remove(last()) |
| Reverse view | Collections.reverse(list) (mutates!) | No direct method | No method | sortedSet.descendingIterator() |
The problems with this:
- Different method names for the same logical operation across types.
- Missing operations —
LinkedHashSethad no clean API for first/last access. - No polymorphism — you couldn't write a single method that accepts "any ordered collection" and works with first/last operations generically.
- Reverse behavior inconsistency —
Collections.reverse()mutates the original list;descendingIterator()gives an iterator, not a view.
The Java 21 Solution: A Unified Interface
Now, regardless of whether you have a List, a Deque, a LinkedHashSet, or a TreeSet, you use the exact same method names. Code becomes:
- Easier to write
- Easier to read
- More generic and reusable
- Self-documenting
8. SequencedCollection Interface Methods & Usage
Interface Definition
1public interface SequencedCollection<E> extends Collection<E> {2 SequencedCollection<E> reversed();3 void addFirst(E e);4 void addLast(E e);5 E getFirst();6 E getLast();7 E removeFirst();8 E removeLast();9}Example: List (Java 21+)
1import java.util.*;2
3public class SequencedListDemo {4 public static void main(String[] args) {5 List<String> list = new ArrayList<>(List.of("B", "C", "D"));6
7 // Access8 System.out.println(list.getFirst()); // B9 System.out.println(list.getLast()); // D10
11 // Add12 list.addFirst("A");13 list.addLast("Z");14 System.out.println(list); // [A, B, C, D, Z]15
16 // Remove17 list.removeFirst(); // removes A18 list.removeLast(); // removes Z19 System.out.println(list); // [B, C, D]20
21 // Reverse view22 SequencedCollection<String> reversed = list.reversed();23 System.out.println(reversed); // [D, C, B]24 }25}Output
1B2D3[A, B, C, D, Z]4[B, C, D]5[D, C, B]Line-by-Line Explanation
| Line | Operation | Result |
|---|---|---|
getFirst() | Returns first element without removing | "B" |
getLast() | Returns last element without removing | "D" |
addFirst("A") | Inserts at position 0 | [A, B, C, D] |
addLast("Z") | Appends to end | [A, B, C, D, Z] |
removeFirst() | Removes element at index 0 | [B, C, D, Z] |
removeLast() | Removes last element | [B, C, D] |
reversed() | Returns a reversed view | [D, C, B] |
reversed() returns a view, not a copy. Changes to the view reflect in the original list and vice versa.Example: Deque (Java 21+)
1Deque<String> deque = new ArrayDeque<>(List.of("B", "C", "D"));2
3System.out.println(deque.getFirst()); // B4System.out.println(deque.getLast()); // D5
6deque.addFirst("A");7deque.addLast("Z");8System.out.println(deque); // [A, B, C, D, Z]9
10deque.removeFirst();11deque.removeLast();12System.out.println(deque); // [B, C, D]13
14System.out.println(deque.reversed()); // [D, C, B]Note: The method names are now identical to the List example above. This is the power of the common interface.
9. SequencedSet Interface Methods & Usage
Interface Definition
1public interface SequencedSet<E> extends SequencedCollection<E>, Set<E> {2 SequencedSet<E> reversed(); // overrides return type to SequencedSet3}SequencedSet inherits all methods from SequencedCollection and additionally enforces no duplicates from Set.
Example: LinkedHashSet (Java 21+)
1import java.util.*;2
3public class SequencedLinkedHashSetDemo {4 public static void main(String[] args) {5 LinkedHashSet<String> set = new LinkedHashSet<>(List.of("B", "C", "D"));6
7 // Access8 System.out.println(set.getFirst()); // B9 System.out.println(set.getLast()); // D10
11 // Add — unique values12 set.addFirst("A");13 set.addLast("Z");14 System.out.println(set); // [A, B, C, D, Z]15
16 // Duplicate handling with addFirst17 set.addFirst("C"); // C already exists!18 // C is moved to the first position19 System.out.println(set); // [C, A, B, D, Z]20
21 // Remove22 set.removeFirst(); // removes C23 set.removeLast(); // removes Z24 System.out.println(set); // [A, B, D]25
26 // Reverse view27 System.out.println(set.reversed()); // [D, B, A]28 }29}Output
1B2D3[A, B, C, D, Z]4[C, A, B, D, Z]5[A, B, D]6[D, B, A]Special Behavior: `addFirst()` / `addLast()` with Duplicates
addFirst("C") on a LinkedHashSet that already contains "C":
- The duplicate is not inserted again (Set contract: no duplicates).
- Instead, "C" is moved to the first position.
- This is unique behavior specific to SequencedSet.Example: SortedSet / TreeSet (Java 21+)
1SortedSet<Integer> sortedSet = new TreeSet<>(Set.of(14, 5, 7));2// Internally stored as: [5, 7, 14]3
4System.out.println(sortedSet.getFirst()); // 55System.out.println(sortedSet.getLast()); // 146
7// Add — sorted automatically8sortedSet.add(2); // goes to first (smallest)9sortedSet.add(20); // goes to last (largest)10System.out.println(sortedSet); // [2, 5, 7, 14, 20]11
12// Reverse view13System.out.println(sortedSet.reversed()); // [20, 14, 7, 5, 2]addFirst() and addLast() throw UnsupportedOperationException on SortedSet/TreeSet.
Because elements are sorted automatically, "add at first" or "add at last" has no deterministic meaning. Use add(element) instead — the set will place it in the correct sorted position.10. SequencedMap Interface Methods & Usage
Interface Definition
1public interface SequencedMap<K, V> extends Map<K, V> {2 SequencedMap<K, V> reversed();3 Map.Entry<K, V> firstEntry();4 Map.Entry<K, V> lastEntry();5 Map.Entry<K, V> pollFirstEntry();6 Map.Entry<K, V> pollLastEntry();7 V putFirst(K k, V v);8 V putLast(K k, V v);9 SequencedSet<K> sequencedKeySet();10 SequencedCollection<V> sequencedValues();11 SequencedSet<Map.Entry<K, V>> sequencedEntrySet();12}Method Summary
| Method | Description |
|---|---|
firstEntry() | Returns (but does not remove) the first key-value entry |
lastEntry() | Returns (but does not remove) the last key-value entry |
pollFirstEntry() | Removes and returns the first entry |
pollLastEntry() | Removes and returns the last entry |
putFirst(k, v) | Inserts/moves entry to the first position |
putLast(k, v) | Inserts/moves entry to the last position |
reversed() | Returns a reversed view of the map |
sequencedKeySet() | Returns keys as a SequencedSet |
sequencedValues() | Returns values as a SequencedCollection |
sequencedEntrySet() | Returns entries as a SequencedSet |
Example: LinkedHashMap (Java 21+)
1import java.util.*;2
3public class SequencedLinkedHashMapDemo {4 public static void main(String[] args) {5 LinkedHashMap<Integer, String> map = new LinkedHashMap<>();6 map.put(100, "B");7 map.put(200, "C");8 map.put(300, "D");9
10 // Access entries11 System.out.println(map.firstEntry()); // 100=B12 System.out.println(map.lastEntry()); // 300=D13
14 // Add at first and last15 map.putFirst(400, "A");16 map.putLast(500, "Z");17 System.out.println(map);18 // {400=A, 100=B, 200=C, 300=D, 500=Z}19
20 // Remove first and last21 map.pollFirstEntry(); // removes 400=A22 map.pollLastEntry(); // removes 500=Z23 System.out.println(map);24 // {100=B, 200=C, 300=D}25
26 // Reverse view27 System.out.println(map.reversed());28 // {300=D, 200=C, 100=B}29 }30}Output
1100=B2300=D3{400=A, 100=B, 200=C, 300=D, 500=Z}4{100=B, 200=C, 300=D}5{300=D, 200=C, 100=B}Example: SortedMap / TreeMap (Java 21+)
1SortedMap<Integer, String> sortedMap = new TreeMap<>();2sortedMap.put(200, "B");3sortedMap.put(50, "A");4sortedMap.put(400, "C");5// Internally sorted by key: {50=A, 200=B, 400=C}6
7System.out.println(sortedMap.firstEntry()); // 50=A8System.out.println(sortedMap.lastEntry()); // 400=C9
10// Reverse view11System.out.println(sortedMap.reversed());12// {400=C, 200=B, 50=A}putFirst() and putLast() throw UnsupportedOperationException on SortedMap/TreeMap.
The map is sorted by key. The position of any entry is determined by the key's natural ordering — you cannot force an entry to a specific position. Use put(key, value) and let the sort handle placement.11. UnsupportedOperationException Sorted Types
This is a nuanced but frequently tested point.
Which Methods Throw on Sorted Collections?
| Collection Type | Method | Behavior |
|---|---|---|
TreeSet (SortedSet) | addFirst(e) | ❌ UnsupportedOperationException |
TreeSet (SortedSet) | addLast(e) | ❌ UnsupportedOperationException |
TreeSet (SortedSet) | add(e) | ✅ Inserts in sorted position |
TreeMap (SortedMap) | putFirst(k, v) | ❌ UnsupportedOperationException |
TreeMap (SortedMap) | putLast(k, v) | ❌ UnsupportedOperationException |
TreeMap (SortedMap) | put(k, v) | ✅ Inserts in sorted key order |
Why?
Sorted collections delegate element positioning to their internal comparator/natural ordering. Telling a TreeSet to "add this at the first position" contradicts its fundamental contract — what if the element doesn't belong at the first position by sort order?
addFirst() / addLast() / putFirst() / putLast() on a sorted collection, you will get a runtime UnsupportedOperationException. Always use plain add() / put() for sorted types and let the comparator decide placement.12. Interview Notes
Q1: What are the three new interfaces introduced in Java 21's collection framework?
SequencedCollection, SequencedSet, and SequencedMap — all in java.util.
Q2: Why were these interfaces needed?
Before Java 21, collections with a defined order (insertion or sorted) each used different method names for accessing/adding/removing first and last elements, and there was no unified interface for these operations. The new interfaces provide a common, consistent API across all ordered collections.
Q3: What are the three conditions that make a collection "sequenced"?
- Predictable iteration — maintains insertion or sorted order consistently.
- First/last element access and manipulation — supports get, add, and remove at both ends.
- Reversible view — supports obtaining a reversed view of the collection.
Q4: Why is Queue not part of SequencedCollection?
Queue fails Conditions 2 and 3. It only allows insertion at the tail and removal at the head (FIFO). You cannot access the last element, cannot add at the front, and cannot reverse a queue. Its one-directional nature disqualifies it.
Q5: Why is PriorityQueue excluded?
PriorityQueue fails Condition 1. It uses a heap internally, which only guarantees the head (min or max). The iteration order of the remaining elements is heap-order, which is neither insertion-order nor consistently sorted. Conditions 2 and 3 are therefore also meaningless.
Q6: What is the difference between `SequencedCollection` and `SequencedSet`?
SequencedCollection allows duplicates (like List, Deque). SequencedSet extends both SequencedCollection and Set, enforcing the no-duplicate constraint of Set. Collections like LinkedHashSet and TreeSet implement SequencedSet.
Q7: What happens when you call `addFirst("C")` on a `LinkedHashSet` that already contains `"C"`?
Since Set does not allow duplicates, "C" is not inserted again. Instead, the existing "C" is repositioned to the first element. This move-to-front behavior is the defined semantics for SequencedSet.addFirst() when a duplicate is encountered.
Q8: Why do `addFirst()` and `addLast()` throw `UnsupportedOperationException` on `TreeSet`/`TreeMap`?
Sorted collections position elements based on their natural ordering or a comparator. Specifying a position (first or last) contradicts this contract — the sort determines position, not the caller. Use add() / put() instead.
Q9: What is the difference between `reversed()` and `Collections.reverse()`?
| Aspect | reversed() | Collections.reverse() |
|---|---|---|
| Type | Returns a view | Mutates the original list in-place |
| New collection created? | No | No |
| Applicable to | Any SequencedCollection | List only |
| Reflected in original? | Yes — view is live | N/A (original was changed) |
| Available since | Java 21 | Java 1.2 |
Q10: What does `SequencedMap` add over regular `Map`?
SequencedMap adds: firstEntry(), lastEntry(), pollFirstEntry(), pollLastEntry(), putFirst(), putLast(), reversed(), sequencedKeySet(), sequencedValues(), sequencedEntrySet().
13. Common Mistakes
Mistake 1: Using `addFirst()` / `addLast()` on `TreeSet` or `TreeMap`
1TreeSet<Integer> ts = new TreeSet<>();2ts.add(5);3ts.addFirst(1); // ❌ UnsupportedOperationException!✅ Correct: Use add() — the sorted set will place it correctly.
1ts.add(1); // ✅ Goes to the front if it's the smallestMistake 2: Thinking `reversed()` creates a new independent collection
1List<String> original = new ArrayList<>(List.of("A", "B", "C"));2List<String> rev = (List<String>) original.reversed();3rev.addFirst("Z"); // This modifies the ORIGINAL list too!4System.out.println(original); // [A, B, C, Z] ← Z appears at end (reversed view's first = original's last)reversed() returns a live view backed by the original. Any structural modification through the reversed view is reflected in the original.Mistake 3: Assuming `Queue` qualifies as a sequenced collection
Queue maintains insertion order, so students sometimes assume it passes Condition 1 and therefore qualifies. It fails Conditions 2 and 3.
Mistake 4: Confusing `pollFirstEntry()` with `firstEntry()`
1map.firstEntry(); // ✅ Reads but does NOT remove2map.pollFirstEntry(); // ✅ Reads AND removespoll = remove; first/last = peek only.
14. Best Practices
- Prefer
getFirst()/getLast()over index-based access forList— it's more expressive and readable.
- Use
SequencedCollectionas the parameter type in method signatures when you only need ordered first/last operations — this makes your code work withList,Deque, andLinkedHashSetpolymorphically.
1// Good — generic and reusable2public void printEnds(SequencedCollection<String> col) {3 System.out.println("First: " + col.getFirst());4 System.out.println("Last: " + col.getLast());5}- Never use
addFirst()/addLast()on sorted collections — always use plainadd()/put().
- Use
reversed()for read-only reverse traversal and avoid modifying through a reversed view to prevent confusion.
- For
SequencedMap, prefersequencedKeySet()andsequencedValues()overkeySet()andvalues()when you need to operate on those views in a sequenced manner.
15. Practice Questions
Easy
- Name the three new interfaces introduced in Java 21's collection framework.
- What are the three conditions a collection must satisfy to be considered "sequenced"?
- Why is
HashSetnot part ofSequencedCollection? - What is the return type of
reversed()on aList? - What is the difference between
firstEntry()andpollFirstEntry()on aSequencedMap?
Medium
- Explain why
Queuewas left out ofSequencedCollectioneven though it maintains insertion order. - What happens when you call
addFirst("X")on aLinkedHashSetthat already contains"X"? - Write a method that accepts a
SequencedCollectionand prints the first and last elements without using index-based access. - Why is
SequencedSetneeded as a separate interface instead of puttingLinkedHashSetdirectly underSequencedCollection? - Explain the difference between
reversed()andCollections.reverse().
Hard
- Draw the complete Java 21 collection hierarchy from memory, including which classes implement which new interfaces. Justify each placement using the three conditions.
- What happens internally when you call
addFirst("C")on aLinkedHashSetcontaining["B", "C", "D"]? What does the resulting set look like and why? - Why do
addFirst()andaddLast()throwUnsupportedOperationExceptiononTreeSet, even thoughTreeSetimplementsSequencedSet? Isn't that a contract violation? - Write a generic utility method
that removes the first element and adds it to the last position using the new Java 21 API.void rotateLeft(SequencedCollection col) - A colleague says "I'll use
SequencedCollectioninstead ofListeverywhere now." What are the trade-offs of this approach? When is it appropriate and when is it not?
16. Summary
Revision Bullets
- Java 21 adds three interfaces:
SequencedCollection,SequencedSet,SequencedMap— inserted into the existing hierarchy. - A collection is "sequenced" if it satisfies: (1) predictable iteration, (2) first/last access + manipulation, (3) reversible view.
ListandDeque→ extendSequencedCollection.LinkedHashSetandTreeSet→ implementSequencedSet(extendsSequencedCollection+Set; no duplicates).LinkedHashMapandTreeMap→ implementSequencedMap.Queue,PriorityQueue,HashSet,HashMap,Hashtable→ excluded; fail one or more conditions.SequencedSetis separate fromSequencedCollectionbecause sets prohibit duplicates; a separate interface enforces that contract.- New unified API:
getFirst(),getLast(),addFirst(),addLast(),removeFirst(),removeLast(),reversed(). reversed()returns a live view backed by the original — not a copy.addFirst()/addLast()on sorted collections (TreeSet,TreeMap) throwUnsupportedOperationException— sorted position is determined by the comparator, not the caller.SequencedMapadds:firstEntry(),lastEntry(),pollFirstEntry(),pollLastEntry(),putFirst(),putLast(),reversed(),sequencedKeySet(),sequencedValues(),sequencedEntrySet().- The core motivation: before Java 21, there was no common interface for ordered collections — each type used different method names for identical logical operations.
End of Chapter — Java 21 Sequenced Collections, SequencedSet & SequencedMap
Mastery check
How well can you recall this?
Finished this lesson?