Java 21 sequenced collections: getFirst, getLast, reversed

For years, getting the last element of a List meant list.get(list.size() - 1), and a LinkedHashSet couldn't do it at all. Java 21 adds one shared set of methods to every ordered collection. Here is what's new, which classes have it, and the traps to avoid.

Five boxes in a row: java (yellow, marked first), spring, kafka, redis and ai (red, marked last). On the left, addFirst, getFirst and removeFirst point at the first box; on the right, addLast, getLast and removeLast point at the last. A dashed arrow labelled reversed, a view not a copy, leads to the same words in reverse order. A dark bar lists where the methods now exist: List, Deque, LinkedHashSet, SortedSet, LinkedHashMap, SortedMap.
Fig. 1 — One set of first/last methods, on every collection that has an order.

Quick question: how do you get the last element of each of these in Java 17?

  • A List: list.get(list.size() - 1)
  • A Deque: deque.getLast()
  • A SortedSet: set.last()
  • A LinkedHashSet: …loop through every element and keep the last one.

Four ordered collections, four different answers, and one with no good answer at all. The same mess applied to “first element”, “add at the front” and “iterate in reverse”. Java 21 fixed it with sequenced collections (JEP 431): new interfaces that give every ordered collection the same methods.

// Java 21
list.getLast();
deque.getLast();
sortedSet.getLast();
linkedHashSet.getLast();   // finally

What is a sequenced collection?

A sequenced collection is a collection whose elements have a defined order: there’s a first element, a last element, and everything in between in a known sequence. Lists, deques, LinkedHashSet and sorted sets all qualify. A HashSet does not, since its order is undefined.

Java 21 added three interfaces to the collections framework:

SequencedCollection

interface SequencedCollection<E> extends Collection<E> {
    SequencedCollection<E> reversed();
    void addFirst(E e);
    void addLast(E e);
    E getFirst();
    E getLast();
    E removeFirst();
    E removeLast();
}

List and Deque now extend it, so every ArrayList, LinkedList and ArrayDeque has these methods.

// Java 21
List<String> list = new ArrayList<>(List.of("a", "b", "c"));

list.getFirst();        // "a"     (was list.get(0))
list.getLast();         // "c"     (was list.get(list.size() - 1))
list.addFirst("z");     // [z, a, b, c]
list.addLast("y");      // [z, a, b, c, y]
list.removeFirst();     // returns "z"
list.removeLast();      // returns "y"

SequencedSet

A sequenced set is a SequencedCollection with no duplicates. LinkedHashSet implements it, and SortedSet (so TreeSet) extends it.

// Java 21
var tags = new LinkedHashSet<>(List.of("java", "spring", "ai"));

tags.getFirst();     // "java"
tags.getLast();      // "ai"
tags.reversed();     // [ai, spring, java]

tags.addFirst("ai"); // already there, so it MOVES to the front: [ai, java, spring]

That last line is worth remembering: on a LinkedHashSet, addFirst and addLast reposition an existing element instead of ignoring it.

SequencedMap

Maps get the same treatment. LinkedHashMap implements SequencedMap, and SortedMap (so TreeMap) extends it.

// Java 21
var scores = new LinkedHashMap<String, Integer>();
scores.put("asha", 90);
scores.put("ravi", 75);
scores.put("meena", 88);

scores.firstEntry();          // asha=90
scores.lastEntry();           // meena=88
scores.putFirst("meena", 95); // moves meena to the front, with the new value
                              // {meena=95, asha=90, ravi=75}
scores.pollLastEntry();       // removes and returns ravi=75
scores.reversed();            // {asha=90, meena=95}

SequencedMap also adds sequencedKeySet(), sequencedValues() and sequencedEntrySet(), which return sequenced views, so you can write map.sequencedKeySet().reversed().

“Sequenced collections didn’t add a new data structure. They gave existing ones a common vocabulary.”

Which classes have the new methods?

Interface Implemented by
SequencedCollection List (ArrayList, LinkedList, …), Deque (ArrayDeque, …)
SequencedSet LinkedHashSet, and via SortedSet: TreeSet
SequencedMap LinkedHashMap, and via SortedMap: TreeMap
none HashSet, HashMap: no defined order, so no first or last

Collections also gained unmodifiableSequencedCollection, unmodifiableSequencedSet and unmodifiableSequencedMap wrappers.

reversed() returns a view, not a copy

reversed() doesn’t copy anything. It returns a live view of the same collection in the opposite order. Changes flow both ways:

List<String> list = new ArrayList<>(List.of("a", "b", "c"));
List<String> rev = list.reversed();   // [c, b, a]

list.add("d");
System.out.println(rev);              // [d, c, b, a]: sees the change

rev.set(0, "D");
System.out.println(list);             // [a, b, c, D]: writes go through

That makes reversed() cheap (no copying), and it means you can now iterate any sequenced collection backwards with a plain for-each loop:

for (var tag : tags.reversed()) { ... }

If you need an independent copy, make one: new ArrayList<>(list.reversed()).

Traps to know

Immutable collections still throw. List.of(...), Set.copyOf(...) and friends are sequenced, but unmodifiable, so addFirst and removeLast throw UnsupportedOperationException. getFirst, getLast and reversed work fine.

Sorted collections can’t take addFirst or addLast. A TreeSet decides element order with its comparator, so you can’t put an element “first”. treeSet.addFirst(x) throws UnsupportedOperationException. Use add.

Empty collections throw, they don’t return null. getFirst() on an empty list throws NoSuchElementException, unlike list.stream().findFirst(), which gives you an Optional. Check isEmpty() first when the list might be empty.

ArrayList.addFirst is slow on big lists. It shifts every element one place, so it’s O(n). If you add at the front often, use an ArrayDeque (or LinkedList) instead.

Map entries from firstEntry() are snapshots. map.firstEntry().setValue(...) throws UnsupportedOperationException. Use put to change a value.

Before and after

Task Before Java 21 Java 21
Last element of a list list.get(list.size() - 1) list.getLast()
First element of a LinkedHashSet set.iterator().next() set.getFirst()
Last element of a LinkedHashSet loop through all of it set.getLast()
First entry of a LinkedHashMap map.entrySet().iterator().next() map.firstEntry()
Iterate a list backwards ListIterator from the end, or Collections.reverse on a copy for (var x : list.reversed())

Key takeaways

  • Java 21 added SequencedCollection, SequencedSet and SequencedMap (JEP 431).
  • Every ordered collection now has getFirst(), getLast(), addFirst(), addLast(), removeFirst(), removeLast() and reversed().
  • Maps get firstEntry(), lastEntry(), putFirst(), putLast(), pollFirstEntry(), pollLastEntry().
  • reversed() is a live view, not a copy.
  • Watch for UnsupportedOperationException on immutable and sorted collections and NoSuchElementException on empty ones.

Frequently asked questions

What are sequenced collections in Java 21?

New collection interfaces (SequencedCollection, SequencedSet, SequencedMap) that give every collection with a defined order the same methods for working with its first and last elements and for reversing it.

How do I get the last element of a list in Java?

From Java 21, call list.getLast(). On older versions, use list.get(list.size() - 1).

Does HashSet support getFirst() in Java 21?

No. A HashSet has no defined order, so it isn’t a sequenced collection. Use a LinkedHashSet if you need insertion order with first and last access.

Does reversed() create a new list?

No. It returns a view of the same list in reverse order. Changes to either one show up in the other.

Why does getFirst() throw an exception on an empty list?

It follows the existing Deque.getFirst() behaviour and throws NoSuchElementException. Check isEmpty() first, or use stream().findFirst() if you want an Optional.

Next in Modern Java: text blocks, for writing JSON, SQL and prompts without escape characters.

Comments

LEAVE A COMMENT
No sign-up. Comments appear after a quick review.