Working with Sequenced Collections (Java 21+)
1. Understanding SequencedCollection Interface
| Aspect | Detail |
|---|---|
| Package | java.util.SequencedCollection |
| Implementations | List, Deque, LinkedHashSet |
| Provides | Unified 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]
| Method | Detail |
|---|---|
addFirst(e) | Insert at start |
addLast(e) | Insert at end |
3. Using getFirst() and getLast() Methods
| Method | Throws |
|---|---|
getFirst() | NoSuchElementException if empty |
getLast() | NoSuchElementException if empty |
4. Using removeFirst() and removeLast() Methods
| Method | Returns |
|---|---|
removeFirst() | Removed element |
removeLast() | Removed element |
5. Using reversed() Method
| Aspect | Detail |
|---|---|
| Returns | Reverse-ordered VIEW (not copy) |
| Mutations | Reflected in original |
| Constant time | No element copying |
6. Understanding SequencedSet Interface
| Implementations | Detail |
|---|---|
LinkedHashSet | Insertion order |
SortedSet/TreeSet | Comparator order |
reversed() | Returns SequencedSet |
7. Understanding SequencedMap Interface
| Implementations | Detail |
|---|---|
LinkedHashMap, TreeMap | Both implement |
| Methods | firstEntry, 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
| Method | Returns |
|---|---|
firstEntry() | First key-value or null if empty |
lastEntry() | Last key-value or null if empty |
9. Using pollFirstEntry() and pollLastEntry() Methods
| Method | Behavior |
|---|---|
pollFirstEntry() | Remove + return first |
pollLastEntry() | Remove + return last |
| Empty | Returns null (no exception) |
10. Converting Legacy Collections to Sequenced
| Legacy | Already Sequenced? |
|---|---|
ArrayList, LinkedList | Yes (via List) |
LinkedHashSet, LinkedHashMap | Yes (auto-upgraded in Java 21+) |
HashSet, HashMap | No — wrap in LinkedHashSet/LinkedHashMap |
TreeSet, TreeMap | Yes |