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
Loading compiler…
Four collections with a well-defined order, four different vocabularies, and one of them needs a loop.
The new interfaces
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.
Where they slot into the hierarchy
SequencedCollectionis implemented byList,Deque,SortedSetandLinkedHashSet.SequencedSetsits betweenSetand the ordered set implementations:LinkedHashSet,TreeSetand anySortedSet.SequencedMapis implemented byLinkedHashMap,TreeMapand anySortedMap.HashSetandHashMapare excluded, because they have no defined encounter order — which is exactly the point of the split.
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.