Java Sequenced Collections: SequencedCollection, SequencedSet and SequencedMap (OCP 21)
Java 21 sequenced collections for the OCP exam: getFirst, addLast, removeFirst and reversed on SequencedCollection, SequencedSet and SequencedMap methods, sequenced versus sorted, which classes qualify, unmodifiable views, and a review table of every collection type.
kvi5hnuCode Sprout team member8 min readOn this page
Before Java 21, getting the first or last element depended on the type you had:
list.get(0)andlist.get(list.size() - 1)for aListdeque.getFirst()for aDequesortedSet.first()for aSortedSet- for a
LinkedHashSet, iterating to the end
Java 21 (JEP 431) added three interfaces that give every collection with a defined order one common API.
A sequenced collection has a well-defined encounter order: its elements have a first, a second, and so on up to a last, and you get them in the same order every time. That order may come from insertion, from an index, or from sorting. Sorting isn't required.

SequencedCollection
SequencedCollection<E> extends Collection<E> and adds seven methods:
| Method | Does |
|---|---|
void addFirst(E e) / void addLast(E e) | inserts at the front / back |
E getFirst() / E getLast() | reads the first / last element |
E removeFirst() / E removeLast() | removes and returns the first / last element |
SequencedCollection<E> reversed() | a reverse-ordered view of the same collection |
On an empty collection, getFirst, getLast, removeFirst and removeLast throw NoSuchElementException.
Interfaces that are now sequenced: List, Deque, SequencedSet, SortedSet and NavigableSet. Classes include ArrayList, LinkedList, ArrayDeque, LinkedHashSet, TreeSet, and the immutable lists from List.of. Legacy Vector and Stack are sequenced too.
Not sequenced: HashSet and PriorityQueue. A PriorityQueue hands out elements in priority order, but its iteration order isn't defined. Passing either one where a SequencedCollection is expected is a compile error.
static String ends(SequencedCollection<String> c) {
return c.getFirst() + ".." + c.getLast();
}
ends(new ArrayList<>(List.of("intro", "verse", "chorus"))); // intro..chorus
ends(new TreeSet<>(Set.of("pine", "elm", "oak"))); // elm..pine (sorted)
ends(new LinkedHashSet<>(List.of("red", "amber", "green"))); // red..green (insertion)
ends(new HashSet<>(Set.of("a"))); // DOES NOT COMPILE
Calling these methods through a plain Collection reference doesn't compile (Collection has no getFirst), and neither does calling get(0) through a SequencedCollection reference.
List and Deque already had some of these methods. Deque has had getFirst and addFirst since Java 6, and lists now have them too. Java 21 gave the existing methods a common supertype, and in some cases a more specific return type. For example, List.reversed() returns a List, and Deque.reversed() returns a Deque.
Sequenced isn't the same as sorted
In a sorted collection the collection decides where each element goes. So you can't put an element "first" or "last" yourself:
TreeSet<String> trees = new TreeSet<>(Set.of("pine", "elm", "oak"));
trees.getFirst(); // elm: fine
trees.removeFirst(); // fine: removes elm
trees.addLast("ash"); // UnsupportedOperationException
trees.addFirst("yew"); // UnsupportedOperationException
TreeSet and TreeMap throw UnsupportedOperationException from addFirst/addLast and putFirst/putLast. The exam expects you to understand the idea: a method being declared doesn't guarantee that every implementation supports it. Immutable collections from List.of also throw on every modifying method, including addFirst.
reversed() is a live view
reversed() doesn't copy anything. Reads and writes go through to the original collection:
List<String> list = new ArrayList<>(List.of("a", "b", "c"));
List<String> back = list.reversed(); // [c, b, a]
back.set(0, "Z"); // list is now [a, b, Z]
back.addFirst("d"); // adds at the END of list: [a, b, Z, d]
That makes backward iteration easy: for (String s : list.reversed()). The old ways were ListIterator or Deque.descendingIterator().
SequencedSet
SequencedSet<E> extends both SequencedCollection<E> and Set<E>. It adds no new methods, but it narrows reversed() so it returns a SequencedSet<E>. LinkedHashSet and every SortedSet/NavigableSet (such as TreeSet) are sequenced sets. TreeSet.reversed() returns a NavigableSet.
A set can't contain duplicates, so adding an element that's already present to a LinkedHashSet with addFirst or addLast moves it to that end:
var lights = new LinkedHashSet<>(List.of("red", "amber", "green"));
lights.addFirst("green"); // [green, red, amber]
SequencedMap
SequencedMap<K,V> extends Map<K,V>. It's implemented by LinkedHashMap and by every SortedMap/NavigableMap (such as TreeMap). HashMap isn't sequenced.
| Method | Does |
|---|---|
Map.Entry<K,V> firstEntry() / lastEntry() | reads the first / last pair, or null if empty |
Map.Entry<K,V> pollFirstEntry() / pollLastEntry() | removes and returns the first / last pair, or null if empty |
V putFirst(K, V) / V putLast(K, V) | inserts (or moves) a pair at the front / back |
SequencedMap<K,V> reversed() | a reverse-ordered view of the map |
sequencedKeySet() / sequencedValues() / sequencedEntrySet() | keySet/values/entrySet as sequenced types |
Compare these with the collection methods:
- The method names differ:
firstEntry, notgetFirst, andputFirst, notaddFirst. - The empty-map behavior differs: the map methods return
nullinstead of throwing. SequencedMaphas nogetFirstoraddFirst. Calling either on a map doesn't compile.- The entries returned by
firstEntryand the related methods are unmodifiable snapshots, sosetValuethrows.
SequencedMap<String, Integer> laps = new LinkedHashMap<>();
laps.put("Kai", 71);
laps.put("Noor", 68);
laps.put("Ivo", 74);
laps.putFirst("Ivo", 70); // existing key: value replaced AND moved to the front
laps.firstEntry(); // Ivo=70
laps.sequencedKeySet().reversed(); // [Noor, Kai, Ivo]
SequencedMap<String, Integer> sorted = new TreeMap<>(laps);
sorted.firstEntry(); // Ivo=70: sorted by key, not insertion
sorted.putFirst("Abe", 60); // UnsupportedOperationException
SequencedMap<String, Integer> bad = new HashMap<>(); // DOES NOT COMPILE
Unmodifiable views
Collections.unmodifiableX(...) wraps a collection in a read-only view:
| Method | Since |
|---|---|
Collections.unmodifiableCollection / List / Set / Map | Java 1.2 |
unmodifiableSortedSet / SortedMap / NavigableSet / NavigableMap | 1.2 / 8 |
unmodifiableSequencedCollection / SequencedSet / SequencedMap | Java 21 |
Any change made through the view (add, remove, put, set, addFirst) throws UnsupportedOperationException. The view doesn't freeze the data, though: changes to the underlying collection show through it. A copy (List.copyOf, Set.copyOf, Map.copyOf) is disconnected from the original:
List<String> backing = Arrays.asList("lamp", "desk");
List<String> view = Collections.unmodifiableList(backing);
List<String> copy = List.copyOf(backing);
backing.set(0, "LAMP");
System.out.println(view); // [LAMP, desk] the view sees it
System.out.println(copy); // [lamp, desk] the copy doesn't
view.set(1, "chair"); // UnsupportedOperationException
backing.add("rug"); // UnsupportedOperationException: Arrays.asList is fixed-size
To decide whether a modification works on the exam, check two things: the reference you call it on (a view refuses everything), and the type of the underlying object (Arrays.asList allows set but not add, List.of allows nothing, new ArrayList<>(...) allows everything). Also watch for constructors that copy: new HashSet<>(list) creates a separate set, so later changes to list don't reach it.
Reviewing the collection types
The four main types:
| Type | Duplicates? | Keys and values? | Order |
|---|---|---|---|
List | yes | no | by index (insertion) |
Set | no | no | depends on the class |
Queue / Deque | yes | no | retrieved from the ends in a defined order |
Map | yes, for values (keys unique) | yes | depends on the class |
The classes on the exam:
| Class | Interfaces | Sequenced? | Sorted? | Uses hashCode? | Uses compareTo? | null allowed? |
|---|---|---|---|---|---|---|
ArrayList | List | yes | no | no | no | yes |
LinkedList | List, Deque | yes | no | no | no | yes |
ArrayDeque | Deque | yes | no | no | no | no |
HashSet | Set | no | no | yes | no | yes |
LinkedHashSet | SequencedSet | yes | no | yes | no | yes |
TreeSet | NavigableSet | yes | yes | no | yes | no |
HashMap | Map | no | no | yes | no | yes (one key) |
LinkedHashMap | SequencedMap | yes | no | yes | no | yes (one key) |
TreeMap | NavigableMap | yes | yes | no | yes | values only |
PriorityQueue | Queue | no | by priority | no | yes | no |
Rules worth remembering:
- Anything sorted calls
compareTo(or a comparator), so it can't holdnullelements or keys under natural ordering. - Anything hashed calls
hashCodeandequals.
Choosing a collection
To answer a "which collection should you use" question, first decide the kind: list, set, queue/deque or map. That alone removes most answers. Then match the details:
- Lookup by key →
Map. Keys sorted →TreeMap. Keys in insertion order →LinkedHashMap. - No duplicates →
Set. Sorted →TreeSet. Insertion order →LinkedHashSet. - Access by index, duplicates allowed →
ArrayList. - First-in first-out, or a stack →
ArrayDeque. Highest priority first →PriorityQueue.
What's current
- Sequenced collections (JEP 431) are new in Java 21 and are directly on 1Z0-830.
- No sequenced methods were added or changed in Java 22 through 25.
Exam traps from this article
A complete example
The program calls one SequencedCollection method on four different classes, and rotates elements where that's allowed. It shows TreeSet refusing addLast, and a reversed view writing through to its list. Then it exercises SequencedMap on a LinkedHashMap and a TreeMap, compares an unmodifiable view with a copy, and checks the behavior on empty collections.
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.SequencedCollection;
import java.util.SequencedMap;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
public class Solution {
// Works for any collection with a defined encounter order
static String ends(SequencedCollection<String> c) {
return c.getFirst() + ".." + c.getLast();
}
static void rotate(SequencedCollection<String> c) {
c.addLast(c.removeFirst());
}
public static void main(String[] args) {
// 1. One method, four kinds of sequenced collections
List<String> list = new ArrayList<>(List.of("intro", "verse", "chorus"));
ArrayDeque<String> deque = new ArrayDeque<>(List.of("north", "east", "south"));
LinkedHashSet<String> linkedSet = new LinkedHashSet<>(List.of("red", "amber", "green"));
TreeSet<String> sortedSet = new TreeSet<>(Set.of("pine", "elm", "oak"));
System.out.println("ends: " + ends(list) + ", " + ends(deque) + ", "
+ ends(linkedSet) + ", " + ends(sortedSet));
// 2. Rotating works where the position is ours to choose...
rotate(list);
rotate(deque);
rotate(linkedSet);
System.out.println("rotated: " + list + " " + deque + " " + linkedSet);
// ...but a sorted set decides positions itself
try {
rotate(sortedSet);
} catch (UnsupportedOperationException e) {
System.out.println("TreeSet.addLast: UnsupportedOperationException, set is still " + sortedSet);
}
// 3. LinkedHashSet.addFirst moves an element that is already present
linkedSet.addFirst("green");
System.out.println("green moved to front: " + linkedSet);
// 4. reversed() is a live view, not a copy
List<String> backwards = list.reversed();
backwards.set(0, "OUTRO");
System.out.println("view " + backwards + " changed original " + list);
// 5. SequencedMap
SequencedMap<String, Integer> laps = new LinkedHashMap<>();
laps.put("Kai", 71);
laps.put("Noor", 68);
laps.put("Ivo", 74);
laps.putFirst("Ivo", 70); // existing key: new value, moved to front
laps.putLast("Uma", 69);
System.out.println("laps " + laps + " first " + laps.firstEntry() + " last " + laps.lastEntry());
System.out.println("reversed keys " + laps.sequencedKeySet().reversed()
+ ", polled " + laps.pollFirstEntry() + ", left " + laps);
SequencedMap<String, Integer> sortedLaps = new TreeMap<>(laps);
System.out.println("TreeMap first by key: " + sortedLaps.firstEntry()
+ ", descending view " + sortedLaps.reversed());
// 6. Unmodifiable views vs copies
List<String> backing = Arrays.asList("lamp", "desk");
List<String> view = Collections.unmodifiableList(backing);
List<String> copy = List.copyOf(backing);
backing.set(0, "LAMP");
System.out.println("view sees change " + view + ", copy does not " + copy);
try {
view.set(1, "chair");
} catch (UnsupportedOperationException e) {
System.out.println("writing through the view: UnsupportedOperationException");
}
// 7. Empty sequenced collections
try {
new ArrayList<String>().getFirst();
} catch (java.util.NoSuchElementException e) {
System.out.println("getFirst on empty list: NoSuchElementException; firstEntry on empty map: "
+ new LinkedHashMap<String, Integer>().firstEntry());
}
}
}
Output:
ends: intro..chorus, north..south, red..green, elm..pine
rotated: [verse, chorus, intro] [east, south, north] [amber, green, red]
TreeSet.addLast: UnsupportedOperationException, set is still [oak, pine]
green moved to front: [green, amber, red]
view [OUTRO, chorus, verse] changed original [verse, chorus, OUTRO]
laps {Ivo=70, Kai=71, Noor=68, Uma=69} first Ivo=70 last Uma=69
reversed keys [Uma, Noor, Kai, Ivo], polled Ivo=70, left {Kai=71, Noor=68, Uma=69}
TreeMap first by key: Kai=71, descending view {Uma=69, Noor=68, Kai=71}
view sees change [LAMP, desk], copy does not [lamp, desk]
writing through the view: UnsupportedOperationException
getFirst on empty list: NoSuchElementException; firstEntry on empty map: null
Points to notice:
endsworks unchanged for a list, a deque, an insertion-ordered set and a sorted set.rotateon theTreeSetfailed ataddLast, but only afterremoveFirsthad already removedelm. The set is left with[oak, pine]. Partial changes like this are whyUnsupportedOperationExceptiondeserves attention.putFirst("Ivo", 70)replaced Ivo's value and moved the key to the front.- The
TreeMapcopy orders by key, so its first entry isKai, not the insertion-first key. - The view showed
LAMPand the copy keptlamp.
Common questions
Can I write my own sequenced collection?
Yes. Implement SequencedCollection (or extend AbstractList and friends, which already do). The default methods throw UnsupportedOperationException where an operation makes no sense.
Does reversed().reversed() give back the original?
It gives a view in the original order, and changes through it still affect the same underlying collection.
Is Collections.reverse(list) the same as list.reversed()?
No. Collections.reverse rearranges the list itself (it returns void). reversed() leaves the list alone and returns a backward view of it.
Summary
- Java 21's
SequencedCollectionaddsaddFirst/addLast,getFirst/getLast,removeFirst/removeLastandreversed()to every collection with a defined encounter order. SequencedSetcoversLinkedHashSetand sorted sets.SequencedMapcoversLinkedHashMapandTreeMap, withfirstEntry,pollFirstEntry,putFirstandreversed().HashSet,HashMapandPriorityQueuearen't sequenced. Sorted collections are sequenced but reject positional inserts.reversed()and theCollections.unmodifiableXwrappers return views.copyOfreturns copies.- Choose a collection by kind first (list, set, queue or map), then by order and null rules.
Practice quiz
Test yourself with the sequenced collections quiz: 10 exam-style questions with explanations.
Previous: Java Sorting: Comparable, Comparator, Collections.sort and binarySearch (OCP 21)
Next: Java Generics: Generic Classes, Interfaces, Methods and Type Erasure (OCP 21)
Related reading
- Java Sorting: Comparable, Comparator, Collections.sort and binarySearch (OCP 21)
- Java Map Interface: HashMap, TreeMap and Methods like merge and compute (OCP 21)
- Java Set, Queue and Deque: HashSet, TreeSet, ArrayDeque and Their Methods (OCP 21)
- Java List Interface: ArrayList, LinkedList, Factory Methods and List Operations (OCP 21)
- Java Collections Framework: The Collection Interface and Common Methods (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.