Working with Sequenced Collections (Java 21+)

1. Understanding SequencedCollection Interface

AspectDetail
Packagejava.util.SequencedCollection
ImplementationsList, Deque, LinkedHashSet
ProvidesUnified front/back access + reversed view

2. Using addFirst() and addLast() Methods

Example: SequencedCollection ops

SequencedCollection<String> list = new ArrayList<>(List.of("b", "c"));
list.addFirst("a");
list.addLast("d");        // [a, b, c, d]
MethodDetail
addFirst(e)Insert at start
addLast(e)Insert at end

3. Using getFirst() and getLast() Methods

MethodThrows
getFirst()NoSuchElementException if empty
getLast()NoSuchElementException if empty

4. Using removeFirst() and removeLast() Methods

MethodReturns
removeFirst()Removed element
removeLast()Removed element

5. Using reversed() Method

AspectDetail
ReturnsReverse-ordered VIEW (not copy)
MutationsReflected in original
Constant timeNo element copying

6. Understanding SequencedSet Interface

ImplementationsDetail
LinkedHashSetInsertion order
SortedSet/TreeSetComparator order
reversed()Returns SequencedSet

7. Understanding SequencedMap Interface

ImplementationsDetail
LinkedHashMap, TreeMapBoth implement
MethodsfirstEntry, lastEntry, putFirst, putLast, reversed, sequencedKeySet

8. Using firstEntry() and lastEntry() Methods

Example: SequencedMap

SequencedMap<String, Integer> m = new LinkedHashMap<>();
m.put("a", 1); m.put("b", 2); m.put("c", 3);
Map.Entry<String,Integer> first = m.firstEntry();   // a=1
Map.Entry<String,Integer> last  = m.lastEntry();    // c=3
MethodReturns
firstEntry()First key-value or null if empty
lastEntry()Last key-value or null if empty

9. Using pollFirstEntry() and pollLastEntry() Methods

MethodBehavior
pollFirstEntry()Remove + return first
pollLastEntry()Remove + return last
EmptyReturns null (no exception)

10. Converting Legacy Collections to Sequenced

LegacyAlready Sequenced?
ArrayList, LinkedListYes (via List)
LinkedHashSet, LinkedHashMapYes (auto-upgraded in Java 21+)
HashSet, HashMapNo — wrap in LinkedHashSet/LinkedHashMap
TreeSet, TreeMapYes