Easy java java-21

What are sequenced collections?

The 30 second answer

Java 21 added interfaces for collections with a defined order: sequenced collection, sequenced set and sequenced map. They give one common way to get the first and last element, add or remove at either end, and get a reversed view. Before this, getting the last element meant different code for a list, a deque or a linked hash set. Now it's just getLast.

JEP 431 (final in Java 21) added three interfaces:

  • SequencedCollection: getFirst, getLast, addFirst, addLast, removeFirst, removeLast, reversed.
  • SequencedSet: a sequenced collection with no duplicates; reversed() returns a SequencedSet.
  • SequencedMap: firstEntry, lastEntry, pollFirstEntry, pollLastEntry, putFirst, putLast, reversed, plus sequenced views of keys, values and entries.

They were retrofitted: List and Deque extend SequencedCollection; LinkedHashSet and SortedSet are sequenced sets; LinkedHashMap and SortedMap are sequenced maps.

List<String> list = List.of("a", "b", "c");
list.getLast();            // "c"  (before: list.get(list.size() - 1))
list.reversed();           // view: [c, b, a]

LinkedHashMap<String, Integer> m = new LinkedHashMap<>();
m.putFirst("x", 1);
m.lastEntry();

reversed() returns a view, not a copy. On unmodifiable collections the mutating methods throw UnsupportedOperationException, and addFirst / putFirst on sorted collections also throw, because the comparator decides the order.

Sources: JEP 431: Sequenced Collections, SequencedCollection Javadoc, SequencedMap Javadoc

Sources (0)
See inline citations in the answer above.