Sequenced collections fill a 25-year gap

Java 21 Course · lesson 4 of 15 · 4 min read

Why getting the last element used to need a different incantation for every collection type.

Open this lesson in the learning hub

Key points

  • Getting the first element was list.get(0), deque.peekFirst(), set.iterator().next() - three idioms.
  • Getting the last from a LinkedHashSet had no idiom at all; you iterated the whole thing.
  • JEP 431 added SequencedCollection, SequencedSet and SequencedMap above the existing types.
  • Now getFirst, getLast, addFirst, addLast and reversed() work everywhere order exists.
  • reversed() returns a view, not a copy - changes flow both ways.

Example

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>(List.of("a", "b", "c"));
        LinkedHashSet<String> set = new LinkedHashSet<>(List.of("x", "y", "z"));
        LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
        map.put("one", 1); map.put("two", 2); map.put("three", 3);

        // One vocabulary across all three
        System.out.println("list  first/last : " + list.getFirst() + " / " + list.getLast());
        System.out.println("set   first/last : " + set.getFirst() + " / " + set.getLast());
        System.out.println("map   first/last : " + map.firstEntry() + " / " + map.lastEntry());

        System.out.println("reversed list    : " + list.reversed());
        System.out.println("reversed set     : " + set.reversed());

        // reversed() is a view - mutate through it
        list.reversed().addFirst("z-end");
        System.out.println("after view add   : " + list);
    }
}

Sequenced collections added no new data structure - they added the missing shared vocabulary.

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 Java 21 Course course, and every lesson in it is listed on the Java 21 Course contents page.