Video in progress

Strong Middle 🧺 Collections

What problem did the SequencedCollection interface in Java 21 solve?

There is now a common API for ordered collections: getFirst, getLast, addFirst, addLast, removeFirst, removeLast and reversed(). Before, getting the first or last element was done differently in List, Deque, LinkedHashSet and SortedSet.

📖 Answer

Before Java 21, getting the "last element":

list.get(list.size() - 1);          // List
deque.getLast();                    // Deque
sortedSet.last();                   // SortedSet
// LinkedHashSet: only by iterating to the end

Now:

List<String> list = new ArrayList<>(List.of("a", "b", "c"));
list.getLast();                     // "c"
list.reversed();                    // [c, b, a]: a view, not a copy

LinkedHashMap<String, Integer> m = new LinkedHashMap<>();
m.putFirst("x", 1);                 // SequencedMap
m.firstEntry();
m.sequencedKeySet().reversed();

The hierarchy: SequencedCollection → List, Deque, SequencedSet (→ LinkedHashSet, SortedSet). For maps there is SequencedMap (→ LinkedHashMap, SortedMap).

Subtle points:

  • reversed() returns a view, so changes made through it affect the original collection too;
  • TreeSet.addFirst throws an UnsupportedOperationException, because the comparator determines the order;
  • on immutable lists, addFirst/removeLast throw too;
  • the new method names can collide with a getFirst() you wrote yourself in old code (for example, in a class that implements List with a different return type). That is where the compile error comes from when you move to Java 21.