Skip to main content
PreparationZone Logo
PrepZone

Sequenced Collections

One vocabulary for first, last and reversed across every ordered collection.

Pass checkpoint below

Why this matters

  • Getting the last element used to require a different expression for every collection type, and one of those expressions was a four-line workaround.
  • It is a rare retrofit of the collections framework, so it shows up in "what is new in Java 21" conversations alongside virtual threads.
  • reversed() gives you a view rather than a copy, which is both convenient and a source of surprises if you do not know it.

The problem

Java
Loading compiler…

Four collections with a well-defined order, four different vocabularies, and one of them needs a loop.

The new interfaces

Java
Loading compiler…
SequencedCollection
getFirst() / getLast()Read either end
addFirst() / addLast()Write either end
removeFirst() / removeLast()Take from either end
reversed()A view, not a copy

Implemented by List, LinkedHashSet, SortedSet, LinkedHashMap and SortedMap.

Any collection with a defined order now shares the same vocabulary for both ends, replacing the old mix of getFirst, iterator().next() and listIterator tricks.

Where they slot into the hierarchy

  • SequencedCollection is implemented by List, Deque, SortedSet and LinkedHashSet.
  • SequencedSet sits between Set and the ordered set implementations: LinkedHashSet, TreeSet and any SortedSet.
  • SequencedMap is implemented by LinkedHashMap, TreeMap and any SortedMap.
  • HashSet and HashMap are excluded, because they have no defined encounter order — which is exactly the point of the split.
Java
Loading compiler…

The rest of this guide is part of Pro

Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.

Still to come · 5 sections

  • reversed() is a view
  • SequencedMap in practice
  • An LRU cache, before and after
  • Compatibility notes
  • Common misreadings

Test yourself

Answer these before moving on — recall is what makes it stick.