Sequenced Collections in Java 21
Java 21 (JEP 431) added three interfaces, SequencedCollection, SequencedSet and SequencedMap, for collections with a defined encounter order. They give lists, deques, LinkedHashSet, LinkedHashMap and sorted collections one common set of methods for the first and last elements and a reversed view.
This tutorial shows the new methods, which classes implement them, and the behaviour to watch out for.
1. Why Were Sequenced Collections Added?
Getting the last element used to depend on the type: list.get(list.size() - 1), deque.getLast(), sortedSet.last(), and for a LinkedHashSet there was no direct way at all. Reversing also worked differently everywhere. There was no common type to write a method that accepts "any ordered collection".
2. New Interfaces and Methods
| Interface | Methods | Implemented by |
|---|---|---|
SequencedCollection<E> | addFirst, addLast, getFirst, getLast, removeFirst, removeLast, reversed | List, Deque |
SequencedSet<E> | the above, with reversed() returning a set | LinkedHashSet, SortedSet |
SequencedMap<K,V> | firstEntry, lastEntry, pollFirstEntry, putFirst, putLast, reversed, sequencedKeySet | LinkedHashMap, SortedMap |
3. Practical Examples
Example 1: One method for lists, deques and sets
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.SequencedCollection;
public class SequencedBasics {
// One method that works for lists, deques and linked sets
static String ends(SequencedCollection<String> c) {
return c.getFirst() + " ... " + c.getLast() + " (reversed: " + c.reversed() + ")";
}
public static void main(String[] args) {
List<String> playlist = new ArrayList<>(List.of("intro", "verse", "chorus"));
playlist.addFirst("countdown");
playlist.addLast("outro");
System.out.println("List : " + ends(playlist));
Deque<String> undo = new ArrayDeque<>(List.of("type", "bold", "delete"));
System.out.println("Deque : " + ends(undo));
LinkedHashSet<String> visited = new LinkedHashSet<>(List.of("home", "search", "cart"));
visited.addFirst("cart"); // existing element moves to the front
System.out.println("LinkedHashSet: " + ends(visited));
// Before Java 21 each type needed a different expression for the last element
System.out.println("old list last: " + playlist.get(playlist.size() - 1));
System.out.println("new list last: " + playlist.getLast());
}
}
List : countdown ... outro (reversed: [outro, chorus, verse, intro, countdown]) Deque : type ... delete (reversed: [delete, bold, type]) LinkedHashSet: cart ... search (reversed: [search, home, cart]) old list last: outro new list last: outro
addFirst on a LinkedHashSet moves an existing element to the front instead of adding a duplicate.
Example 2: Sequenced maps and reversed views
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.SequencedMap;
import java.util.TreeMap;
public class SequencedMaps {
public static void main(String[] args) {
SequencedMap<String, Integer> leaderboard = new LinkedHashMap<>();
leaderboard.put("asha", 120);
leaderboard.put("ravi", 95);
leaderboard.putFirst("meera", 150); // insert at the front
leaderboard.putLast("john", 80);
System.out.println("Map : " + leaderboard);
System.out.println("firstEntry : " + leaderboard.firstEntry());
System.out.println("lastEntry : " + leaderboard.lastEntry());
System.out.println("reversed : " + leaderboard.reversed());
System.out.println("pollFirst : " + leaderboard.pollFirstEntry() + " -> " + leaderboard.sequencedKeySet());
// Sorted maps are sequenced too
TreeMap<Integer, String> grades = new TreeMap<>(java.util.Map.of(90, "A", 75, "B", 60, "C"));
System.out.println("TreeMap last: " + grades.lastEntry());
// reversed() on an unmodifiable list is a read-only view
List<String> fixed = Collections.unmodifiableList(List.of("x", "y", "z"));
System.out.println("view : " + fixed.reversed());
try {
fixed.reversed().addFirst("w");
} catch (UnsupportedOperationException e) {
System.out.println("addFirst on unmodifiable view: UnsupportedOperationException");
}
}
}
Map : {meera=150, asha=120, ravi=95, john=80}
firstEntry : meera=150
lastEntry : john=80
reversed : {john=80, ravi=95, asha=120, meera=150}
pollFirst : meera=150 -> [asha, ravi, john]
TreeMap last: 90=A
view : [z, y, x]
addFirst on unmodifiable view: UnsupportedOperationException
reversed() returns a view, not a copy. Changes to the original are visible through the view, and an unmodifiable collection gives an unmodifiable view.
4. The New Type Hierarchy
5. Important Points and Best Practices
- Use
SequencedCollectionas a parameter type when a method needs order but not indexes. getFirst()andgetLast()throwNoSuchElementExceptionon an empty collection.- Sorted collections (
TreeSet,TreeMap) rejectaddFirstandputFirstwithUnsupportedOperationException, because order comes from the comparator. HashSetandHashMaphave no defined order and are not sequenced.
6. Summary
- Java 21 (JEP 431) added
SequencedCollection,SequencedSetandSequencedMap. - Ordered collections now share
getFirst,getLast,addFirst,addLastandreversed. - Maps gain
firstEntry,lastEntry,putFirstandputLast. reversed()returns a live view, not a copy.
Related Tutorials
7. References
Frequently Asked Questions (FAQ)
Q1. What are sequenced collections in Java 21?
Collections with a defined encounter order that share a common interface, SequencedCollection, with methods for the first and last elements and a reversed view.
Q2. Does HashMap implement SequencedMap?
No. HashMap has no defined order. LinkedHashMap and sorted maps such as TreeMap implement it.
Q3. Does reversed() copy the collection?
No. It returns a view backed by the original collection.
Q4. What happens when getFirst() is called on an empty list?
It throws NoSuchElementException.