Sequenced collections (Java 21)

Collections · lesson 31 of 42 · 4 min read

Read and write both ends of any ordered collection with one API, new in Java 21.

Open this lesson in the learning hub

Key points

  • Java 21 gave every ordered collection one API: SequencedCollection, SequencedSet, SequencedMap.
  • getFirst, getLast, addFirst, removeLast now work on a plain List.
  • Before 21 a LinkedHashSet had no way to read its last element without walking the whole set.
  • reversed() hands back a view, not a copy, so it is free and it writes through.
  • LinkedHashMap gained firstEntry, lastEntry, putFirst and pollLastEntry.
  • Immutable lists are sequenced too: you can read both ends, but every mutator still throws.

Example

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>(List.of("a", "b", "c"));
        System.out.println("getFirst / getLast : " + list.getFirst() + " / " + list.getLast());
        list.addFirst("start");
        list.addLast("end");
        System.out.println("addFirst + addLast : " + list);
        System.out.println("reversed() view    : " + list.reversed());

        LinkedHashSet<String> set = new LinkedHashSet<>(List.of("x", "y", "z"));
        System.out.println("set.getLast()      : " + set.getLast() + "   (no iteration needed)");
        System.out.println("set.reversed()     : " + set.reversed());

        LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
        map.put("one", 1);
        map.put("two", 2);
        map.put("three", 3);
        System.out.println("firstEntry         : " + map.firstEntry());
        System.out.println("lastEntry          : " + map.lastEntry());
        map.putFirst("zero", 0);
        System.out.println("putFirst           : " + map.keySet());
        System.out.println("pollLastEntry      : " + map.pollLastEntry() + "  leaves " + map.keySet());
        System.out.println("reversed map keys  : " + map.reversed().keySet());

        Deque<String> dq = new ArrayDeque<>(List.of("p", "q"));
        System.out.println("Deque is sequenced : " + (dq instanceof SequencedCollection));
    }
}

If your code ends in size() - 1, Java 21 has a method that says what you meant.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Collections course, and every lesson in it is listed on the Collections contents page.