Sequenced collections
Java 21 added three interfaces for collections with a defined order: SequencedCollection, SequencedSet and SequencedMap. They give every ordered collection the same methods for both ends and a reversed() view. This page explains how they were fitted into the existing collection types, shows each method running, builds a recent-items list and an LRU cache, measures two speed traps, and shows the code that the change broke.
Contents
What sequenced collections are and why they were added
Many collections have a defined encounter order: the order in which iteration returns the elements. A ListDequeLinkedHashSetTreeSet
| Type | Last element |
|---|---|
List | list.get(list.size() - 1) |
Deque | deque.getLast() |
SortedSet | set.last() |
LinkedHashSet | Iterate over every element; no direct way |
LinkedHashMap | Iterate over every entry; no direct way |
JEP 431 added three interfaces and inserted them into the existing hierarchy, so that every ordered type implements them without any change to user code:
, a parent ofSequencedCollection andList , declaresDeque ,getFirst ,getLast ,addFirst ,addLast ,removeFirst andremoveLast .reversed , a parent ofSequencedSet and implemented bySortedSet , narrowsLinkedHashSet to return a set.reversed() , a parent ofSequencedMap and implemented bySortedMap , addsLinkedHashMap ,firstEntry ,lastEntry ,pollFirstEntry ,pollLastEntry ,putFirst ,putLast and ordered views of its keys, values and entries.reversed
Most of the new methods are defaultLinkedHashSetLinkedHashMapgetLast()reversed()ReverseOrderListViewArrayList
| Method | Since | Replaces | Best for |
|---|---|---|---|
getFirst()getLast() | Java 21 | get(0)get(size() - 1)first() | Reading the ends of any ordered collection |
addFirstaddLast | Java 21 (Java 6 on Deque | add(0, e) | Lists, deques, moving an element in a LinkedHashSet |
removeFirstremoveLast | Java 21 (Java 6 on Deque | remove(0)pollFirst() | Deques; trimming bounded lists |
reversed() | Java 21 | Collections.reversedescendingSet() | Iterating backwards without copying |
putFirstpollFirstEntry | Java 21 (Java 6 on NavigableMap | Rebuilding a LinkedHashMap | Ordered caches and queues of keys |
The examples were compiled and run on JDK 21.
SequencedCollection: both ends and a reversed view
The endsSequencedCollectionLinkedHashSetTreeSet
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.SequencedCollection;
import java.util.TreeSet;
public class SequencedApi {
// One method for every ordered collection: List, Deque, LinkedHashSet, TreeSet...
static String ends(SequencedCollection<String> c) {
return c.getFirst() + ".." + c.getLast();
}
public static void main(String[] args) {
List<String> list = new ArrayList<>(List.of("b", "c", "d"));
list.addFirst("a");
list.addLast("e");
System.out.println("list: " + list + " ends " + ends(list));
// reversed() is a live view, not a copy
List<String> back = list.reversed();
back.removeFirst(); // removes "e" from the original list
System.out.println("reversed view: " + back);
System.out.println("original now: " + list);
System.out.println("reversed().reversed() is the original list: "
+ (back.reversed() == list));
// LinkedHashSet.addFirst moves an element that is already present
LinkedHashSet<String> recent = new LinkedHashSet<>(List.of("home", "docs", "blog"));
recent.addFirst("blog");
System.out.println("LinkedHashSet: " + recent + " ends " + ends(recent));
// A sorted set decides the order itself, so it refuses addFirst
TreeSet<String> sorted = new TreeSet<>(List.of("pear", "apple", "fig"));
System.out.println("TreeSet: " + sorted + " ends " + ends(sorted));
try {
sorted.addFirst("zebra");
} catch (UnsupportedOperationException e) {
System.out.println("TreeSet.addFirst: UnsupportedOperationException");
}
try {
List.of("x").addFirst("w");
} catch (UnsupportedOperationException e) {
System.out.println("List.of(..).addFirst: UnsupportedOperationException");
}
try {
new ArrayList<String>().getFirst();
} catch (NoSuchElementException e) {
System.out.println("getFirst on empty list: NoSuchElementException");
}
}
}
Output:
list: [a, b, c, d, e] ends a..e
reversed view: [d, c, b, a]
original now: [a, b, c, d]
reversed().reversed() is the original list: true
LinkedHashSet: [blog, home, docs] ends blog..docs
TreeSet: [apple, fig, pear] ends apple..pear
TreeSet.addFirst: UnsupportedOperationException
List.of(..).addFirst: UnsupportedOperationException
getFirst on empty list: NoSuchElementException
andaddFirst turnedaddLast into[b, c, d] .[a, b, c, d, e] is a view backed by the original. Removing the first element of the view removedreversed() , the last element of the original, and reversing the view again returned the original list object itself.e- On a
,LinkedHashSet moved the existing element to the front instead of adding a duplicate.addFirst("blog") - A
can report its ends, apple and pear, but its comparator decides positions, soTreeSet throwsaddFirst .UnsupportedOperationException - Lists from
throw for every modifying method, including the new ones.List.of on an empty list throwsgetFirst , whileNoSuchElementException would throwget(0) .IndexOutOfBoundsException
SequencedMap
The program uses a LinkedHashMapTreeMap
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.SequencedMap;
import java.util.TreeMap;
public class SequencedMapDemo {
public static void main(String[] args) {
SequencedMap<String, Integer> visits = new LinkedHashMap<>();
visits.put("home", 10);
visits.put("docs", 4);
visits.put("blog", 7);
System.out.println("map: " + visits);
System.out.println("firstEntry: " + visits.firstEntry());
System.out.println("lastEntry: " + visits.lastEntry());
visits.putFirst("blog", 8); // existing key: new value and moved to the front
visits.putLast("about", 1);
System.out.println("after putFirst/putLast: " + visits);
System.out.println("reversed view: " + visits.reversed());
System.out.println("last two keys: "
+ visits.sequencedKeySet().reversed().stream().limit(2).toList());
Map.Entry<String, Integer> polled = visits.pollFirstEntry();
System.out.println("pollFirstEntry: " + polled + ", map now " + visits);
// Entries returned by these methods are snapshots and cannot be changed
try {
visits.firstEntry().setValue(99);
} catch (UnsupportedOperationException e) {
System.out.println("firstEntry().setValue: UnsupportedOperationException");
}
// TreeMap is a SequencedMap too, but its order comes from the keys
TreeMap<String, Integer> sorted = new TreeMap<>(Map.of("b", 2, "a", 1));
System.out.println("TreeMap first: " + sorted.firstEntry() + ", reversed: "
+ sorted.reversed());
try {
sorted.putFirst("z", 26);
} catch (UnsupportedOperationException e) {
System.out.println("TreeMap.putFirst: UnsupportedOperationException");
}
}
}
Output:
map: {home=10, docs=4, blog=7}
firstEntry: home=10
lastEntry: blog=7
after putFirst/putLast: {blog=8, home=10, docs=4, about=1}
reversed view: {about=1, docs=4, home=10, blog=8}
last two keys: [about, docs]
pollFirstEntry: blog=8, map now {home=10, docs=4, about=1}
firstEntry().setValue: UnsupportedOperationException
TreeMap first: a=1, reversed: {b=2, a=1}
TreeMap.putFirst: UnsupportedOperationException
on an existing key both updated the value from 7 to 8 and moved the entry to the front.putFirst("blog", 8) added a new key at the end.putLast- The last two keys came from reversing the key-set view and taking two, without walking the whole map.
removed and returnedpollFirstEntry , which makes ablog=8 usable as a simple FIFO queue of keys.LinkedHashMap- Entries returned by
and similar methods are snapshots, sofirstEntry throws. UsesetValue to change a value.put supports both ends and reversing but notTreeMap , because the keys decide the order.putFirst
A recent-items list and an LRU cache
Ordered sets and maps are the natural tools for "most recently used" lists and caches, and the new methods make them shorter. The file sequence reopens a.txt
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.SequencedCollection;
import java.util.SequencedMap;
public class RecentItems {
// Most-recently-used list: newest first, at most 3 entries, no duplicates
static void open(LinkedHashSet<String> recent, String file) {
recent.addFirst(file); // moves the file to the front if present
if (recent.size() > 3) {
recent.removeLast(); // drop the oldest
}
}
// Least-recently-used cache: access order plus removeEldestEntry
static final class Lru<K, V> extends LinkedHashMap<K, V> {
private static final long serialVersionUID = 1L;
private final int capacity;
Lru(int capacity) {
super(16, 0.75f, true); // true = order by access, not insertion
this.capacity = capacity;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > capacity;
}
}
public static void main(String[] args) {
LinkedHashSet<String> recent = new LinkedHashSet<>();
for (String f : List.of("a.txt", "b.txt", "c.txt", "a.txt", "d.txt")) {
open(recent, f);
System.out.println("open " + f + " -> " + recent);
}
Lru<String, Integer> cache = new Lru<>(2);
cache.put("x", 1);
cache.put("y", 2);
cache.get("x"); // x becomes the most recently used
cache.put("z", 3); // evicts y, the least recently used
System.out.println("LRU after get(x), put(z): " + cache);
System.out.println("eldest: " + cache.firstEntry() + ", newest: " + cache.lastEntry());
System.out.println("newest first: " + cache.reversed().keySet());
// A read-only view that keeps the ordered type
SequencedCollection<String> view = Collections.unmodifiableSequencedCollection(recent);
System.out.println("read-only view first: " + view.getFirst());
try {
view.removeFirst();
} catch (UnsupportedOperationException e) {
System.out.println("read-only view removeFirst: UnsupportedOperationException");
}
SequencedMap<String, Integer> roMap = Collections.unmodifiableSequencedMap(cache);
System.out.println("read-only map last: " + roMap.lastEntry());
}
}
Output:
open a.txt -> [a.txt]
open b.txt -> [b.txt, a.txt]
open c.txt -> [c.txt, b.txt, a.txt]
open a.txt -> [a.txt, c.txt, b.txt]
open d.txt -> [d.txt, a.txt, c.txt]
LRU after get(x), put(z): {x=1, z=3}
eldest: x=1, newest: z=3
newest first: [z, x]
read-only view first: d.txt
read-only view removeFirst: UnsupportedOperationException
read-only map last: z=3
- Reopening
moved it to the front instead of duplicating it. Openinga.txt made four entries, sod.txt dropped the oldest,removeLast() .b.txt - The
map is built with access order (Lru in the constructor), sotrue movedget("x") to the most recent end. Addingx then evictedz throughy .removeEldestEntry - In such a map,
is the eldest andfirstEntry() the newest;lastEntry() lists the newest first without copying.reversed().keySet() andCollections.unmodifiableSequencedCollection are new in Java 21. They give read-only wrappers that keepunmodifiableSequencedMap andgetFirst , which the olderlastEntry cannot offer.unmodifiableCollection
For more on these maps, see
Speed: one big win and one trap
The program times the last element of a one-million-element LinkedHashSetArrayListArrayDequeremoveFirst
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.function.LongSupplier;
public class EndsSpeed {
public static void main(String[] args) {
LinkedHashSet<Integer> set = new LinkedHashSet<>();
for (int i = 0; i < 1000000; i++) {
set.add(i);
}
// Last element of a LinkedHashSet: before Java 21 you had to iterate
time("LinkedHashSet last, by iterating", () -> {
Integer last = null;
Iterator<Integer> it = set.iterator();
while (it.hasNext()) {
last = it.next();
}
return last;
});
time("LinkedHashSet.getLast()", () -> set.getLast());
// removeFirst on an ArrayList shifts every remaining element
time("ArrayList: removeFirst 100,000x", () -> {
List<Integer> list = new ArrayList<>(set.stream().limit(100000).toList());
long sum = 0;
while (!list.isEmpty()) {
sum += list.removeFirst();
}
return sum;
});
time("ArrayDeque: removeFirst 100,000x", () -> {
ArrayDeque<Integer> deque = new ArrayDeque<>(set.stream().limit(100000).toList());
long sum = 0;
while (!deque.isEmpty()) {
sum += deque.removeFirst();
}
return sum;
});
}
static void time(String label, LongSupplier work) {
long best = Long.MAX_VALUE;
long result = 0;
for (int run = 0; run < 3; run++) {
long t0 = System.nanoTime();
result = work.getAsLong();
best = Math.min(best, System.nanoTime() - t0);
}
System.out.printf("%-34s result %,14d best of 3: %,12d ns%n", label, result, best);
}
}
Output:
LinkedHashSet last, by iterating result 999,999 best of 3: 9,747,564 ns
LinkedHashSet.getLast() result 999,999 best of 3: 338 ns
ArrayList: removeFirst 100,000x result 4,999,950,000 best of 3: 366,630,884 ns
ArrayDeque: removeFirst 100,000x result 4,999,950,000 best of 3: 1,907,572 ns
- Finding the last element by iteration visited all one million elements.
read the tail of the linked list and was thousands of times faster. That alone is a reason to movegetLast() code to Java 21.LinkedHashSet - The trap:
reads as cheap, but it isArrayList.removeFirst() , which shifts every remaining element one place left. Emptying the list from the front is quadratic, and it was more than a hundred times slower thanremove(0) , which only moves its head index.ArrayDeque - The new uniform names do not change the cost of the underlying data structure. Use a
for queue-like work at the front.Deque
Which classes implement the new interfaces
Rather than relying on a list from the documentation, the program asks the running JDK which interfaces each common class implements.
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.SequencedCollection;
import java.util.SequencedMap;
import java.util.SequencedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.CopyOnWriteArrayList;
public class WhoImplements {
public static void main(String[] args) {
List<Class<?>> classes = List.of(ArrayList.class, LinkedList.class,
CopyOnWriteArrayList.class, ArrayDeque.class, LinkedHashSet.class, TreeSet.class,
ConcurrentSkipListSet.class,
HashSet.class, LinkedHashMap.class, TreeMap.class, HashMap.class);
System.out.printf("%-22s %-20s %-12s %s%n", "class", "SequencedCollection",
"SequencedSet", "SequencedMap");
for (Class<?> c : classes) {
System.out.printf("%-22s %-20s %-12s %s%n", c.getSimpleName(),
mark(SequencedCollection.class, c), mark(SequencedSet.class, c),
mark(SequencedMap.class, c));
}
}
static String mark(Class<?> iface, Class<?> c) {
return iface.isAssignableFrom(c) ? "yes" : "-";
}
}
Output:
class SequencedCollection SequencedSet SequencedMap
ArrayList yes - -
LinkedList yes - -
CopyOnWriteArrayList yes - -
ArrayDeque yes - -
LinkedHashSet yes yes -
TreeSet yes yes -
ConcurrentSkipListSet yes yes -
HashSet - - -
LinkedHashMap - - yes
TreeMap - - yes
HashMap - - -
All lists and deques are SequencedCollectionLinkedHashSetSequencedSetHashSetHashMapSequencedCollectionLinkedHashMapkeySet()SetsequencedKeySet()
The compatibility breaks
Adding methods to interfaces as widely implemented as List--release 17--release 21
import java.net.URI;
import java.util.List;
import java.util.Locale;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
// Code that compiled on Java 17 and breaks on Java 21 because of the new interface methods
public class Compatibility {
public static void main(String[] args) {
check("17", "a list subclass with its own getFirst()", """
import java.util.*;
class MyList<E> extends ArrayList<E> {
public Optional<E> getFirst() { return isEmpty() ? Optional.empty()
: Optional.of(get(0)); }
}""");
check("21", "the same class on Java 21", """
import java.util.*;
class MyList<E> extends ArrayList<E> {
public Optional<E> getFirst() { return isEmpty() ? Optional.empty()
: Optional.of(get(0)); }
}""");
check("21", "a class that is both a List and a Deque", """
import java.util.*;
abstract class Both<E> extends AbstractList<E> implements Deque<E> { }""");
}
static void check(String release, String label, String source) {
JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diags = new DiagnosticCollector<>();
String name = source.contains("MyList") ? "MyList" : "Both";
JavaFileObject file = new SimpleJavaFileObject(
URI.create("string:///" + name + ".java"), JavaFileObject.Kind.SOURCE) {
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return source;
}
};
boolean ok = javac.getTask(null, null, diags, List.of("--release", release, "-d",
System.getProperty("java.io.tmpdir")), null, List.of(file)).call();
System.out.println("--release " + release + ", " + label + ": " + (ok ? "compiles" : ""));
for (Diagnostic<? extends JavaFileObject> d : diags.getDiagnostics()) {
if (d.getKind() == Diagnostic.Kind.ERROR) {
String text = d.getMessage(Locale.ENGLISH).strip();
System.out.println(" error: " + String.join(" ", text.split("\\s*\\n\\s*")));
}
}
}
}
Output:
--release 17, a list subclass with its own getFirst(): compiles
--release 21, the same class on Java 21:
error: getFirst() in MyList cannot implement getFirst() in java.util.List return type java.util.Optional<E> is not compatible with E
--release 21, a class that is both a List and a Deque:
error: types java.util.Deque<E> and java.util.List<E> are incompatible; both define reversed(), but with unrelated return types
- A list subclass that defined its own
returninggetFirst() compiled for Java 17. On Java 21 it now overridesOptional<E> , which returnsList.getFirst() , so the incompatible return type is an error. Such a method must be renamed.E - A class that is both a
and aList inherits twoDeque methods with unrelated return types and must declare its own. That is exactly whatreversed() does: itsLinkedList returnsreversed() , which satisfies both interfaces.LinkedList - Both breaks appear only when the code is recompiled, so a full build against Java 21, including libraries that subclass collections, is the way to find them before release.
Which one to use
| Need | Use |
|---|---|
| A method that accepts any ordered collection | A SequencedCollection<E> |
| First or last element | getFirst()getLast() |
| Iterate backwards | for (E e : c.reversed()) |
| Frequent removal at the front | ArrayDequeArrayList |
| Recently used items without duplicates | LinkedHashSetaddFirstremoveLast |
| LRU cache | LinkedHashMapremoveEldestEntry |
Ordered keys of a LinkedHashMap | sequencedKeySet() |
| Read-only view that keeps the ends | Collections.unmodifiableSequencedCollection |
For the underlying structures and their costs, see