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 List keeps insertion order, a Deque has a head and a tail, a LinkedHashSet remembers insertion order and a TreeSet keeps elements sorted. Before Java 21 there was no common type for "a collection with an order", and each type had its own way to reach the ends:

Getting the last element before Java 21
TypeLast element
Listlist.get(list.size() - 1)
Dequedeque.getLast()
SortedSetset.last()
LinkedHashSetIterate over every element; no direct way
LinkedHashMapIterate 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:

  • SequencedCollection, a parent of List and Deque, declares getFirst, getLast, addFirst, addLast, removeFirst, removeLast and reversed.
  • SequencedSet, a parent of SortedSet and implemented by LinkedHashSet, narrows reversed() to return a set.
  • SequencedMap, a parent of SortedMap and implemented by LinkedHashMap, adds firstEntry, lastEntry, pollFirstEntry, pollLastEntry, putFirst, putLast, reversed and ordered views of its keys, values and entries.

Most of the new methods are default methods written in terms of older ones, and the concrete classes override them where they can do better. LinkedHashSet and LinkedHashMap, for example, already kept a doubly linked list of their entries, so the new getLast() just reads its tail. reversed() never copies: it returns a view object, such as ReverseOrderListView for an ArrayList, that maps each operation onto the original in the opposite direction.

The new methods and what they replace
MethodSinceReplacesBest for
getFirst(), getLast()Java 21get(0), get(size() - 1), first(), iterationReading the ends of any ordered collection
addFirst, addLastJava 21 (Java 6 on Deque)add(0, e)Lists, deques, moving an element in a LinkedHashSet
removeFirst, removeLastJava 21 (Java 6 on Deque)remove(0), pollFirst()Deques; trimming bounded lists
reversed()Java 21Collections.reverse on a copy, descendingSet()Iterating backwards without copying
putFirst, pollFirstEntry on mapsJava 21 (Java 6 on NavigableMap)Rebuilding a LinkedHashMapOrdered caches and queues of keys

The examples were compiled and run on JDK 21.

SequencedCollection: both ends and a reversed view

The ends method accepts any SequencedCollection and works on a list, a LinkedHashSet and a TreeSet alike. The program also checks the cases where the methods refuse to work.

Java
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:

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
  • addFirst and addLast turned [b, c, d] into [a, b, c, d, e].
  • reversed() is a view backed by the original. Removing the first element of the view removed e, the last element of the original, and reversing the view again returned the original list object itself.
  • On a LinkedHashSet, addFirst("blog") moved the existing element to the front instead of adding a duplicate.
  • A TreeSet can report its ends, apple and pear, but its comparator decides positions, so addFirst throws UnsupportedOperationException.
  • Lists from List.of throw for every modifying method, including the new ones.
  • getFirst on an empty list throws NoSuchElementException, while get(0) would throw IndexOutOfBoundsException.

SequencedMap

The program uses a LinkedHashMap of page visits in insertion order, moves and adds entries at both ends, and then repeats a few calls on a TreeMap, whose order comes from its keys.

Java
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:

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
  • putFirst("blog", 8) on an existing key both updated the value from 7 to 8 and moved the entry to the front. putLast added a new key at the end.
  • The last two keys came from reversing the key-set view and taking two, without walking the whole map.
  • pollFirstEntry removed and returned blog=8, which makes a LinkedHashMap usable as a simple FIFO queue of keys.
  • Entries returned by firstEntry and similar methods are snapshots, so setValue throws. Use put to change a value.
  • TreeMap supports both ends and reversing but not putFirst, because the keys decide the order.

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 to show it moving to the front, and the cache is read once between writes to show access order at work.

Java
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:

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 a.txt moved it to the front instead of duplicating it. Opening d.txt made four entries, so removeLast() dropped the oldest, b.txt.
  • The Lru map is built with access order (true in the constructor), so get("x") moved x to the most recent end. Adding z then evicted y through removeEldestEntry.
  • In such a map, firstEntry() is the eldest and lastEntry() the newest; reversed().keySet() lists the newest first without copying.
  • Collections.unmodifiableSequencedCollection and unmodifiableSequencedMap are new in Java 21. They give read-only wrappers that keep getFirst and lastEntry, which the older unmodifiableCollection cannot offer.

For more on these maps, see TreeMap and LinkedHashMap.

Speed: one big win and one trap

The program times the last element of a one-million-element LinkedHashSet the old way and the new way, then empties a 100,000-element ArrayList and ArrayDeque from the front with removeFirst. Each case runs 3 times and the fastest run is shown. This is a rough comparison on a 2-CPU Linux machine with JDK 21; the ratios matter more than the numbers.

Java
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:

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. getLast() read the tail of the linked list and was thousands of times faster. That alone is a reason to move LinkedHashSet code to Java 21.
  • The trap: ArrayList.removeFirst() reads as cheap, but it is remove(0), 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 than ArrayDeque, which only moves its head index.
  • The new uniform names do not change the cost of the underlying data structure. Use a Deque for queue-like work at the front.

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.

Java
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:

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 SequencedCollections. LinkedHashSet and the sorted sets are also SequencedSets. HashSet and HashMap have no defined order and implement none of them, so a method that takes a SequencedCollection rejects them at compile time. Note that the key set of a LinkedHashMap is ordered, but keySet() still returns a plain Set; call sequencedKeySet() to get the ordered type.

The compatibility breaks

Adding methods to interfaces as widely implemented as List can break existing code that already had methods with the same names. The program compiles the same source with --release 17 and --release 21 to show two kinds of break.

Java
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:

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 getFirst() returning Optional<E> compiled for Java 17. On Java 21 it now overrides List.getFirst(), which returns E, so the incompatible return type is an error. Such a method must be renamed.
  • A class that is both a List and a Deque inherits two reversed() methods with unrelated return types and must declare its own. That is exactly what LinkedList does: its reversed() returns LinkedList, which satisfies both interfaces.
  • 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

Choosing a sequenced type and method
NeedUse
A method that accepts any ordered collectionA SequencedCollection<E> parameter
First or last elementgetFirst(), getLast()
Iterate backwardsfor (E e : c.reversed()), no copy
Frequent removal at the frontArrayDeque, not ArrayList
Recently used items without duplicatesLinkedHashSet with addFirst and removeLast
LRU cacheLinkedHashMap in access order with removeEldestEntry
Ordered keys of a LinkedHashMapsequencedKeySet()
Read-only view that keeps the endsCollections.unmodifiableSequencedCollection and friends

For the underlying structures and their costs, see ArrayList vs LinkedList and queues and deques.