Week 65 — What are sequenced collections?

Question of the Week #65
What are sequenced collections?
2 Replies
Eric McIntyre
Eric McIntyre9mo ago
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 Lists and Deques 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 TreeSetimplementing SequencedSet as well. Another special case is LinkedHashSet which has an encounter order and was changed to implement SequencedSet as well.
Eric McIntyre
Eric McIntyre9mo ago
Similarly to SequencedCollection, an interface SequencedMap extending Map was introduced with methods for accessing Maps 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 SortedMaps (like TreeMap) as well as LinkedHashMap implement SequencedMap.
📖 Sample answer from dan1st
Want results from more Discord servers?
Add your server