00:00

Sequenced Collections in Java 21

Last updated: · Standard (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

InterfaceMethodsImplemented by
SequencedCollection<E>addFirst, addLast, getFirst, getLast, removeFirst, removeLast, reversedList, Deque
SequencedSet<E>the above, with reversed() returning a setLinkedHashSet, SortedSet
SequencedMap<K,V>firstEntry, lastEntry, pollFirstEntry, putFirst, putLast, reversed, sequencedKeySetLinkedHashMap, SortedMap

3. Practical Examples

Example 1: One method for lists, deques and sets

SequencedBasics.java
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());
    }
}
Output
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

SequencedMaps.java
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");
        }
    }
}
Output
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

Where the sequenced interfaces fit SequencedCollection sits between Collection and List or Deque. SequencedSet extends it for LinkedHashSet and SortedSet. SequencedMap sits between Map and LinkedHashMap or SortedMap. COLLECTIONS Collection unordered root SequencedCollection first, last, reversed List / Deque already ordered MAPS Map unordered root SequencedMap firstEntry, putFirst LinkedHashMap / SortedMap ordered maps
Figure 1: Existing ordered collections now share these interfaces; HashSet and HashMap are unchanged.

5. Important Points and Best Practices

  • Use SequencedCollection as a parameter type when a method needs order but not indexes.
  • getFirst() and getLast() throw NoSuchElementException on an empty collection.
  • Sorted collections (TreeSet, TreeMap) reject addFirst and putFirst with UnsupportedOperationException, because order comes from the comparator.
  • HashSet and HashMap have no defined order and are not sequenced.

6. Summary

  • Java 21 (JEP 431) added SequencedCollection, SequencedSet and SequencedMap.
  • Ordered collections now share getFirst, getLast, addFirst, addLast and reversed.
  • Maps gain firstEntry, lastEntry, putFirst and putLast.
  • reversed() returns a live view, not a copy.

Related Tutorials

7. References