What are sequenced collections in Java 21?

Java 21 added the interfaces SequencedCollection, SequencedSet and SequencedMap for collections with a defined order. They give every ordered collection the same methods to read, add and remove at both ends, and to get a reversed view.

Key Points: • New methods: getFirst(), getLast(), addFirst(), addLast(), removeFirst(), removeLast() and reversed(). • List, Deque, LinkedHashSet and SortedSet now implement SequencedCollection. • SequencedMap (implemented by LinkedHashMap and SortedMap) adds firstEntry(), lastEntry(), pollFirstEntry(), putFirst() and reversed(). • Before Java 21, getting the last element meant list.get(list.size() - 1), and for a LinkedHashSet you had to iterate through it. • reversed() returns a view, not a copy, so changes to the view affect the original.

Code Example:

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;

public class SequencedDemo {

    public static void main(String[] args) {
        List<String> list = new ArrayList<>(List.of("B", "C"));
        list.addFirst("A");
        list.addLast("D");
        System.out.println(list + " first=" + list.getFirst() + " last=" + list.getLast());
        System.out.println("Reversed view: " + list.reversed());

        LinkedHashSet<Integer> set = new LinkedHashSet<>(List.of(10, 20, 30));
        System.out.println("Set last: " + set.getLast());

        LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
        map.put("one", 1);
        map.put("two", 2);
        map.putFirst("zero", 0);
        System.out.println(map + " first=" + map.firstEntry() + " last=" + map.lastEntry());
    }
}

Output:

[A, B, C, D] first=A last=D Reversed view: [D, C, B, A] Set last: 30 {zero=0, one=1, two=2} first=zero=0 last=two=2

Good to Know: This is a quick way to show you follow recent Java versions. Mention the problem it solves, which was inconsistent APIs for "first" and "last" across List, Deque and LinkedHashSet, rather than just listing the method names.

Interview Tip: A concise interview answer is:

"Java 21 added SequencedCollection, SequencedSet and SequencedMap, which give ordered collections common methods like getFirst, getLast, addFirst, removeLast and reversed. It replaces awkward code such as list.get(list.size() - 1) and iterating a LinkedHashSet to find its last element."

Previous question: What are text blocks in Java?

Next question: Which useful String, Stream and Optional methods were added after Java 8?

More Java 17 and 21 Features interview questions

All Java 17 and 21 Features questions