Collections ·
‹ Previous Next ›
⏱ 5 min read Modified: 2026-12-02

Sequenced Collections in Java 21: SequencedCollection, SequencedSet and SequencedMap

How do you get the last element of a collection in Java 17? For an ArrayList it is list.get(list.size() - 1), for an ArrayDeque — getLast(), for a TreeSet — last(), and for a LinkedHashSet — only by iterating over the whole set. Four collections with a clear order, four different ways. Java 21 gave all of them one common answer: getLast().

Sequenced Collections (JEP 431) are three interfaces added to the Collections Framework in Java 21: SequencedCollection, SequencedSet and SequencedMap. They describe collections with a defined encounter order — collections that have a first and a last element. The interfaces provide uniform methods getFirst(), getLast(), addFirst(), addLast(), removeFirst(), removeLast() and reversed(), which returns a reverse-ordered view of the collection. List, Deque, SortedSet, SortedMap, LinkedHashSet and LinkedHashMap received them — and so did all their implementations.

List<String> tasks = new ArrayList<>(List.of("read", "code", "test"));
tasks.getLast();      // "test"  — instead of tasks.get(tasks.size() - 1)
tasks.reversed();     // [test, code, read] — no copying

Why Sequenced Collections were added

Before Java 21 the Collections Framework had no type for "a collection with an order". List, Deque, SortedSet and LinkedHashSet all had an order, but their common ancestor is Collection, which has none. So the operations "first", "last" and "in reverse order" had different names in each branch of the hierarchy, and LinkedHashSet and LinkedHashMap lacked some of them entirely.

Collection First element before Java 21 Last element before Java 21 Reverse iteration before Java 21 Java 21+
List list.get(0) list.get(list.size() - 1) listIterator(list.size()) + hasPrevious() getFirst(), getLast(), reversed()
Deque getFirst() getLast() descendingIterator()
SortedSet first() last() descendingSet() (on NavigableSet)
LinkedHashSet iterator().next() Full iteration only None — copy into a list
LinkedHashMap entrySet().iterator().next() Full iteration only None — copy into a list

The old methods are still there: first(), descendingSet() and descendingIterator() work as before. Java 21 added a shared vocabulary that every ordered collection understands, plus a shared type for writing methods that accept "any collection with an order".

Sequenced interfaces in the collection hierarchy

JEP 431 inserted three interfaces between existing levels of the hierarchy. SequencedCollection extends Collection, SequencedSet extends both SequencedCollection and Set, and SequencedMap extends Map. The new interfaces became parents of List, Deque, SortedSet and SortedMap; the classes LinkedHashSet and LinkedHashMap implement them directly.

Collection
└── SequencedCollection        (Java 21)
    ├── List                   → ArrayList, LinkedList, Vector, Stack, CopyOnWriteArrayList
    ├── Deque                  → ArrayDeque, LinkedList, LinkedBlockingDeque, ConcurrentLinkedDeque
    └── SequencedSet           (Java 21, also a Set)
        ├── LinkedHashSet
        └── SortedSet → NavigableSet → TreeSet, ConcurrentSkipListSet

Map
└── SequencedMap               (Java 21)
    ├── LinkedHashMap
    └── SortedMap → NavigableMap → TreeMap, ConcurrentSkipListMap

Encounter order does not necessarily mean sorting. In a List or LinkedHashSet the programmer defines the order — by index or by insertion sequence; in a TreeSet or TreeMap the comparator does. That is why addFirst() behaves differently, as shown below. The full hierarchy and the difference between "ordered" and "sorted" collections are covered in Java Collections Framework: Collection Hierarchy and Interfaces.

Collections without a defined order do not implement the Sequenced interfaces: HashSet, HashMap, EnumSet, CopyOnWriteArraySet, IdentityHashMap. Neither does PriorityQueue: it implements Queue, not Deque, and its iterator does not traverse elements in priority order.

The return type of reversed() gets more specific down the hierarchy

reversed() returns the same "kind" of collection: a List for a List, a Deque for a Deque, a SequencedSet for a LinkedHashSet, a NavigableSet for a TreeSet, a NavigableMap for a TreeMap, and a LinkedList for a LinkedList. So after reversed() you still have all the familiar methods of that type, such as get(int) on a list or peekFirst() on a deque.

The SequencedCollection interface: methods and example

SequencedCollection<E> declares seven methods. Only reversed() is abstract; the others are default methods that concrete classes override with more efficient versions. The add and remove methods are optional operations: unmodifiable collections and collections whose order is defined by sorting throw UnsupportedOperationException.

Method What it does Empty collection
E getFirst(), E getLast() Return the first / last element without removing it NoSuchElementException
void addFirst(E e), void addLast(E e) Add an element at the front / end Work as usual
E removeFirst(), E removeLast() Remove and return the first / last element NoSuchElementException
SequencedCollection<E> reversed() Returns a reverse-ordered view of the collection An empty view

For an ArrayList the new methods are short synonyms of index-based operations: addFirst(e) does the same as add(0, e), and removeLast() the same as remove(size() - 1). The cost is unchanged: inserting or removing at the front of an ArrayList shifts the whole array and takes O(n), while ArrayDeque and LinkedList do it in O(1).

import java.util.ArrayList;
import java.util.List;

public class SequencedListExample {
    public static void main(String[] args) {
        List<String> tasks = new ArrayList<>(List.of("read", "code", "test"));

        System.out.println(tasks.getFirst());     // read
        System.out.println(tasks.getLast());      // test

        tasks.addFirst("plan");                   // same as add(0, "plan")
        tasks.addLast("deploy");                  // same as add("deploy")
        System.out.println(tasks);                // [plan, read, code, test, deploy]

        String removed = tasks.removeLast();
        System.out.println(removed + " " + tasks); // deploy [plan, read, code, test]

        System.out.println(tasks.reversed());     // [test, code, read, plan]
    }
}

Output:

read
test
[plan, read, code, test, deploy]
deploy [plan, read, code, test]
[test, code, read, plan]

Deque already had getFirst(), addFirst(), removeFirst() and their end-of-queue counterparts, so for deques Java 21 essentially added only reversed(). The other deque methods — offerFirst(), peekFirst(), pollLast(), which return null on an empty deque instead of throwing — are covered in Queue and Deque Interfaces in Java. The full set of list methods is in List Interface and ArrayList in Java.

The reversed() method: a view, not a copy

reversed() neither creates a new collection nor rearranges elements. It returns a view — a wrapper over the original collection that reads it from the other end. The call is O(1) regardless of size, changes to the original are immediately visible in the view, and changes made through the view (if the original is modifiable) go to the original.

import java.util.ArrayList;
import java.util.List;

public class ReversedViewExample {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>(List.of(1, 2, 3));
        List<Integer> reversed = numbers.reversed();   // a view, not a copy

        numbers.add(4);
        System.out.println(reversed);       // [4, 3, 2, 1] — sees changes to the original

        reversed.add(0);                    // add() to the end of the view = to the start of the original
        System.out.println(numbers);        // [0, 1, 2, 3, 4]

        reversed.set(0, 40);                // the view's first element is the original's last
        System.out.println(numbers);        // [0, 1, 2, 3, 40]

        for (int n : numbers.reversed()) {  // iterate from the end without indexes or iterators
            System.out.print(n + " ");      // 40 3 2 1 0
        }
        System.out.println();

        List<Integer> copy = new ArrayList<>(numbers.reversed()); // an independent copy
        copy.clear();
        System.out.println(numbers);        // [0, 1, 2, 3, 40]
    }
}

Output:

[4, 3, 2, 1]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 40]
40 3 2 1 0
[0, 1, 2, 3, 40]

The most common use is iterating from the end: for (var x : list.reversed()) or list.reversed().stream(). If you need a separate reversed collection, copy the view: new ArrayList<>(list.reversed()). Do not confuse reversed() with Collections.reverse(list): the latter rearranges the list itself in place and returns nothing (see Collections Class in Java). Other collection views — subList(), headSet(), keySet() — are described in Backed Collections in Java; reversed() follows the same rules.

reversed() works on unmodifiable collections too

List.of(1, 2, 3).reversed() returns [3, 2, 1] without error: reading through a view is always allowed. The original's restrictions carry over to the view — add() through List.of(...).reversed() throws UnsupportedOperationException, just like List.of(...) itself.

The SequencedSet interface: LinkedHashSet and TreeSet

SequencedSet<E> is a SequencedCollection that is also a Set: no duplicates, and reversed() returns a SequencedSet. It is implemented by LinkedHashSet (insertion order) and every SortedSet — TreeSet, ConcurrentSkipListSet (sort order). They share the same methods, but addFirst()/addLast() behave differently.

  • LinkedHashSet: addFirst(e) puts the element at the front; if it was already in the set, the element moves to the front. A plain add() leaves an existing element where it is.
  • TreeSet: addFirst() and addLast() throw UnsupportedOperationException — the comparator decides an element's position. getFirst() works like the old first(), and reversed() like descendingSet().
import java.util.LinkedHashSet;
import java.util.List;
import java.util.SequencedSet;
import java.util.TreeSet;

public class SequencedSetExample {
    public static void main(String[] args) {
        SequencedSet<String> recent = new LinkedHashSet<>(List.of("a.txt", "b.txt", "c.txt"));
        recent.addFirst("c.txt");            // already present — moves to the front
        System.out.println(recent);          // [c.txt, a.txt, b.txt]
        System.out.println(recent.getLast()); // b.txt

        SequencedSet<Integer> sorted = new TreeSet<>(List.of(30, 10, 20));
        System.out.println(sorted.getFirst() + " " + sorted.getLast()); // 10 30
        System.out.println(sorted.reversed());                          // [30, 20, 10]
        try {
            sorted.addFirst(5);              // the sort order decides the position, not us
        } catch (UnsupportedOperationException e) {
            System.out.println("TreeSet.addFirst: " + e.getClass().getSimpleName());
        }
    }
}

Output:

[c.txt, a.txt, b.txt]
b.txt
10 30
[30, 20, 10]
TreeSet.addFirst: UnsupportedOperationException

Moving an element in a LinkedHashSet is handy for "recently opened files" lists: open a file, call addFirst(), and it is at the front without a separate remove(). More on LinkedHashSet is in Set Interface in Java: HashSet and LinkedHashSet; on TreeSet and navigation — in SortedSet, NavigableSet and TreeSet in Java.

The SequencedMap interface: firstEntry, pollLastEntry, putFirst

SequencedMap<K, V> is an ordered map. It is implemented by LinkedHashMap and every SortedMap (TreeMap, ConcurrentSkipListMap). A map is not a collection, so it has its own methods that work with Map.Entry pairs rather than elements.

Method What it does Empty map / notes
firstEntry(), lastEntry() First / last entry without removing it null; the entry is an immutable snapshot
pollFirstEntry(), pollLastEntry() Remove and return the first / last entry null
putFirst(k, v), putLast(k, v) Insert an entry at the front / end LinkedHashMap — an existing key moves; TreeMap — UnsupportedOperationException
reversed() A reverse-ordered view of the map Live, as with collections
sequencedKeySet(), sequencedValues(), sequencedEntrySet() Ordered views of keys, values and entries Have getFirst(), getLast(), reversed(); addFirst() is not supported

Note the difference from collections: on an empty map firstEntry() returns null, while getFirst() on an empty collection throws. The map methods inherited the behavior of NavigableMap, where firstEntry() and pollFirstEntry() have existed since Java 6.

import java.util.Map;
import java.util.SequencedMap;
import java.util.TreeMap;

public class SequencedMapExample {
    public static void main(String[] args) {
        SequencedMap<String, Integer> scores = new TreeMap<>(Map.of("Anna", 90, "Boris", 75, "Vera", 82));

        Map.Entry<String, Integer> first = scores.firstEntry();
        System.out.println(first);                           // Anna=90
        System.out.println(scores.lastEntry());              // Vera=82
        System.out.println(scores.sequencedKeySet().reversed()); // [Vera, Boris, Anna]

        try {
            first.setValue(100);                             // a snapshot, not a live entry
        } catch (UnsupportedOperationException e) {
            System.out.println("setValue: " + e.getClass().getSimpleName());
        }

        System.out.println(scores.pollLastEntry());          // Vera=82
        System.out.println(scores);                          // {Anna=90, Boris=75}

        try {
            scores.putFirst("Zoe", 60);                      // in a TreeMap the keys define the order
        } catch (UnsupportedOperationException e) {
            System.out.println("putFirst: " + e.getClass().getSimpleName());
        }
    }
}

Output:

Anna=90
Vera=82
[Vera, Boris, Anna]
setValue: UnsupportedOperationException
Vera=82
{Anna=90, Boris=75}
putFirst: UnsupportedOperationException

The entry returned by firstEntry() is an immutable snapshot: setValue() on it throws for both TreeMap and LinkedHashMap. To change the value of the first entry, use map.put(map.firstEntry().getKey(), newValue) or map.sequencedEntrySet().getFirst().setValue(newValue) — entries from entrySet are live. An example with putFirst() and putLast() on an insertion-ordered map is in LinkedHashMap and SequencedMap; navigating a TreeMap is covered in TreeMap, SortedMap and NavigableMap in Java.

When the methods throw exceptions

The Sequenced methods throw two exceptions. NoSuchElementException — when there is no element: getFirst(), getLast(), removeFirst(), removeLast() on an empty collection. UnsupportedOperationException — when the collection does not allow the operation.

Collection Reading: getFirst(), getLast(), reversed() Modifying: addFirst(), removeLast(), putFirst()
ArrayList, LinkedList, ArrayDeque, LinkedHashSet, LinkedHashMap Works Works
TreeSet, TreeMap Works addFirst()/addLast()/putFirst()/putLast() — UnsupportedOperationException; removeFirst()/pollFirstEntry() work
List.of(), stream.toList(), Collections.unmodifiable*() Works UnsupportedOperationException
Arrays.asList() Works The size cannot change — UnsupportedOperationException; set() through reversed() works
sequencedKeySet(), sequencedValues(), sequencedEntrySet() Works addFirst()/addLast() — UnsupportedOperationException; removal works
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;

public class SequencedExceptionsExample {
    public static void main(String[] args) {
        try {
            new ArrayList<String>().getFirst();
        } catch (RuntimeException e) {
            System.out.println("empty list getFirst(): " + e.getClass().getSimpleName());
        }

        System.out.println("empty map firstEntry(): " + new LinkedHashMap<String, Integer>().firstEntry());

        try {
            List.of(1, 2).addFirst(0);
        } catch (RuntimeException e) {
            System.out.println("List.of(...).addFirst(): " + e.getClass().getSimpleName());
        }

        List<Integer> fixed = Arrays.asList(1, 2, 3);
        fixed.reversed().set(0, 30);        // set() is allowed on Arrays.asList
        System.out.println(fixed);          // [1, 2, 30]
        try {
            fixed.removeFirst();            // the size cannot change
        } catch (RuntimeException e) {
            System.out.println("Arrays.asList(...).removeFirst(): " + e.getClass().getSimpleName());
        }
    }
}

Output:

empty list getFirst(): NoSuchElementException
empty map firstEntry(): null
List.of(...).addFirst(): UnsupportedOperationException
[1, 2, 30]
Arrays.asList(...).removeFirst(): UnsupportedOperationException

If a collection may be empty, check isEmpty() before getFirst() — unlike peekFirst() on a Deque, the Sequenced methods have no variant that returns null. For unmodifiable views that keep the Sequenced methods, Java 21 added unmodifiableSequencedCollection(), unmodifiableSequencedSet() and unmodifiableSequencedMap() to the Collections class: the plain Collections.unmodifiableCollection() returns a Collection, which has no getFirst().

SequencedCollection as a parameter type

The new interfaces are useful not only for their methods but also as types. Previously a method "return the first and last element" had to be written separately for List, Deque and SortedSet, or it took a Collection and hoped it had an order. Now a single SequencedCollection<T> parameter is enough: the compiler accepts any ordered collection and rejects a HashSet.

import java.util.ArrayDeque;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.SequencedCollection;
import java.util.TreeSet;

public class SequencedParameterExample {

    static <T> String ends(SequencedCollection<T> items) {
        if (items.isEmpty()) {
            return "empty";
        }
        return items.getFirst() + ".." + items.getLast();
    }

    public static void main(String[] args) {
        System.out.println(ends(List.of(3, 1, 2)));                       // 3..2
        System.out.println(ends(new ArrayDeque<>(List.of("x", "y"))));    // x..y
        System.out.println(ends(new LinkedHashSet<>(List.of("b", "a")))); // b..a
        System.out.println(ends(new TreeSet<>(List.of("b", "a"))));       // a..b
        System.out.println(ends(List.of()));                              // empty
        // ends(new HashSet<>(...)) does not compile: HashSet is not a SequencedCollection
    }
}

Output:

3..2
x..y
b..a
a..b
empty

The rule for choosing a type is the same as for other collection interfaces: declare a variable or parameter with the most general type that is enough. If you only iterate — Collection or Iterable; if you need "first, last, from the end" — SequencedCollection, SequencedSet or SequencedMap. Set, Collection and Map do not have getFirst() or putFirst(): with a variable Set<String> s = new LinkedHashSet<>() the call s.getFirst() does not compile.

Compatibility: what breaks when moving to Java 21

For ordinary code the move is seamless: the new methods are default interface methods, and the old ones keep working. Problems appear in three cases.

  • The code is compiled for Java 17 or earlier. list.getFirst() or list.reversed() fails with cannot find symbol. If a project or library must build on an older version, write list.get(0) and list.get(list.size() - 1).
  • Your class already has a method with the same name but a different type. For example, a subclass of ArrayList with Optional<String> getFirst() compiled on Java 17, but on Java 21 it fails with getFirst() in MyList cannot implement getFirst() in List — return type Optional<String> is not compatible with String. The method has to be renamed.
  • Your class implements both List and Deque. Both interfaces declare reversed() with different return types, and without your own override the compiler reports both define reversed(), but with unrelated return types. The JDK solves this for LinkedList by making its reversed() return a LinkedList, which fits both types.

Kotlin and Android are a separate story. Kotlin has long had the extension functions removeFirst() and removeLast() for MutableList; when compiling against JDK 21, the compiler picks the new java.util.List methods instead, and on Android devices whose runtime lacks them the app crashes with NoSuchMethodError. If you write Kotlin for Android, use removeAt(0) and removeAt(lastIndex).

Quick cheat sheet

Need the first or last element of a list — getFirst() / getLast(). Need to iterate from the end — for (var x : c.reversed()). Need a reversed copy — new ArrayList<>(c.reversed()). Need a method for "any ordered collection" — a SequencedCollection<T> parameter. The collection may be empty — check isEmpty() first.

Frequently asked questions

Which Java version introduced Sequenced Collections?

Java 21 (JEP 431), directly as a final feature, without preview. The SequencedCollection, SequencedSet and SequencedMap interfaces live in the java.util package. They do not exist in Java 17 and earlier, so calling getFirst(), getLast() or reversed() on a list does not compile there.

What is the difference between list.getFirst() and list.get(0)?

The result is the same; the exception on an empty list differs: get(0) throws IndexOutOfBoundsException, getFirst() throws NoSuchElementException. The main advantage of getFirst() is that every ordered collection has it, including Deque, TreeSet and LinkedHashSet, which have no indexes.

Does reversed() copy the collection?

No. reversed() returns a view in O(1): changes to the original are visible in it, and changes made through the view go to the original. For an independent copy use new ArrayList<>(list.reversed()). To rearrange the list itself, use Collections.reverse(list).

Why don't HashSet and HashMap implement the Sequenced interfaces?

They have no defined element order: the iteration order depends on hash codes and table capacity and may change after insertions. The "first" element of such a set means nothing. If you need insertion order, use LinkedHashSet and LinkedHashMap; if you need sorting, use TreeSet and TreeMap.

Why does TreeSet.addFirst() throw UnsupportedOperationException?

In a sorted set the comparator, not the programmer, decides where an element goes. You can "add 5 to the front" of the set [10, 20, 30] only with a plain add(5): it ends up first anyway, while add(50) ends up last. The same rule applies to putFirst() and putLast() on a TreeMap.

Practice

Reinforce this lesson with hands-on tasks, each with a level and a time estimate.

All module tasks →

Comments

Please log in or register to have a possibility to add comment.