Skip to content

Lesson 04 · Sequenced Collections

Objectives

After this lesson you will be able to:

  • Use the Java 21 SequencedCollection, SequencedSet, and SequencedMap interfaces.
  • Access first/last elements and obtain a reversed view.
  • Know which existing types gained these methods.

What Java 21 added (JEP 431)

Before Java 21 there was no common type for "a collection with a defined encounter order and both ends reachable." Java 21 adds three interfaces:

  • SequencedCollection<E>addFirst/addLast, getFirst/getLast, removeFirst/ removeLast, and reversed().
  • SequencedSet<E> — a SequencedCollection that is also a Set.
  • SequencedMap<K,V>firstEntry/lastEntry, putFirst/putLast, pollFirstEntry/pollLastEntry, reversed(), plus sequenced keySet/values/entrySet.
java
SequencedCollection<Integer> sc = new ArrayList<>(List.of(1, 2, 3));
sc.getFirst();          // 1   (was list.get(0))
sc.getLast();           // 3   (was list.get(list.size()-1))
sc.addFirst(0);         // [0, 1, 2, 3]
sc.reversed();          // a reversed VIEW: [3, 2, 1, 0]

Which types implement them

TypeNew super-interface
List (e.g. ArrayList, LinkedList)SequencedCollection
Deque (e.g. ArrayDeque)SequencedCollection
LinkedHashSetSequencedSet
SortedSet/TreeSetSequencedSet
LinkedHashMapSequencedMap
SortedMap/TreeMapSequencedMap

Exam trap

reversed() returns a view backed by the original — changes write through, and iterating it costs nothing extra. A plain HashSet/HashMap is NOT sequenced (no defined order), so it has none of these methods. getFirst()/getLast() throw NoSuchElementException on an empty collection.

Beyond the exam

reversed() on a SequencedMap returns a SequencedMap whose encounter order is reversed; on a TreeMap that's the descending order — a cleaner alternative to descendingMap() for simple needs.

Key Takeaways

  • Java 21's SequencedCollection/SequencedSet/SequencedMap unify ordered access: getFirst/getLast, addFirst/addLast, and reversed().
  • List, Deque, LinkedHashSet, TreeSet, LinkedHashMap, and TreeMap implement them; HashSet/HashMap do not (unordered).
  • reversed() is a live view, not a copy; getFirst/getLast throw NoSuchElementException when empty.

Lesson Quiz

Lesson Quiz · Sequenced Collections0 / 4
  1. Which method gives the first element of a List in Java 21?

    • Alist.first()
    • Blist.getFirst()
    • Clist.head()
    • Dlist.peek()
  2. Does HashSet implement SequencedSet?

    • AYes
    • BNo — it has no defined order
    • COnly when sorted
    • DOnly in Java 21
  3. What does reversed() return?

    • AA sorted copy
    • BA live reversed view of the original
    • CA new ArrayList
    • Dnull
  4. What does getFirst() do on an empty List?

    • AReturns null
    • BReturns 0
    • CNoSuchElementException
    • DIndexOutOfBoundsException

Next: Comparison & Sorting. Run the matching code in labs/src/main/java/com/jse21/m05_collections/.