Week 65 — What are sequenced collections?
Question of the Week #65
What are sequenced collections?
2 Replies
Java 21 came with a feature called sequenced collections which added multiple interfaces to the collection hierarchy.
Sequenced collections are special collection that have an "encounter order" i.e. they have a specified order of elements for iteration. Furthermore, it is possible to reverse sequenced collections.
The interface
SequencedCollection
extends Collection
and provides methods for accessing (adding an element or getting/removing the element) the beginning/end (getFirst
, getLast
, addFirst
, addLast
, removeFirst
, removeLast
) and for getting a reversed view (reversed
) on the collection.
All List
s and Deque
s automatically implement SequencedCollection
.
Another interface, SequencedSet
was added which extends both SequencedCollection
and Set
. The reversed
method of SequencedSet
returns an instance of SequencedSet
as opposed to just returning any SequencedCollection
.
As sorted sets always have an encounter order, the interface SortedSet
was changed to extend SequencedSet
resulting in classes like TreeSet
implementing SequencedSet
as well.
Another special case is LinkedHashSet
which has an encounter order and was changed to implement SequencedSet
as well.Similarly to
SequencedCollection
, an interface SequencedMap
extending Map
was introduced with methods for accessing Map
s at the beginning and end (firstEntry
, lastEntry
, pollFirstEntry
, pollLastEntry
, putFirst
, putLast
) and reversing (reversed
).
However, SequencedMap
also contains operations for accessing the keys/values/entries as sequenced collections (sequencedEntrySet
, sequencedKeySet
and sequencedValues
).
Just it is the case with sorted sets and LinkedHashSet
implementing SequencedSet
, all SortedMap
s (like TreeMap
) as well as LinkedHashMap
implement SequencedMap
.📖 Sample answer from dan1st