Sequenced collections
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A sequenced collection is a collection whose elements have a defined order, so it has a first element and a last one. Java 21 added interfaces for this, SequencedCollection, SequencedSet and SequencedMap, with the same methods everywhere: getFirst(), getLast(), addFirst(), reversed() and more.
Java 21: SequencedCollection
Before Java 21, every ordered collection had its own way to reach its ends. A list used list.get(0) and list.get(list.size() - 1). A deque used getFirst() and getLast(). A TreeSet used first() and last().
Example 1 · Both ends of a list, and reversed() as a live view
// Java 21import java.util.ArrayList;import java.util.List;
public class ListEndsDemo { public static void main(String[] args) { List<String> tokens = new ArrayList<>(List.of("T2", "T3")); tokens.addFirst("T1"); tokens.addLast("T4"); System.out.println("Queue: " + tokens);
List<String> backwards = tokens.reversed(); System.out.println("Reversed view: " + backwards);
String served = tokens.removeFirst(); tokens.addLast("T5"); System.out.println("Served " + served + ", queue now " + tokens); System.out.println("Reversed view now: " + backwards);
backwards.addFirst("T6"); System.out.println("After adding through the view: " + tokens); }}Queue: [T1, T2, T3, T4] Reversed view: [T4, T3, T2, T1] Served T1, queue now [T2, T3, T4, T5] Reversed view now: [T5, T4, T3, T2] After adding through the view: [T2, T3, T4, T5, T6]
What this code does
addFirstandaddLastwork on any modifiable list. On anArrayList,addFirstshifts every element, so for heavy front insertion anArrayDequeis still faster.reversed()returns a view, not a copy. After the queue changes, the view shows the change; adding to the front of the reversed view adds to the end of the original.
A LinkedHashSet had no way at all except walking through it with an iterator.
Java 21 added the interface SequencedCollection and made List, Deque, LinkedHashSet and TreeSet all implement it. Now one set of method names works for every ordered collection.
getFirst()/getLast(): read the element at either end.addFirst(e)/addLast(e): insert at either end.removeFirst()/removeLast(): remove and return the element at either end.reversed(): a reversed view of the same collection.
Replacing list.get(list.size() - 1)
Reading the last item of a list is very common: the latest message, the last marks entered, the most recent UPI transaction. The old way, list.get(list.size() - 1), says the same thing twice and invites an off-by-one mistake such as list.get(list.size()).
Example 2 · getFirst and getLast instead of index maths
// Java 21import java.util.ArrayList;import java.util.List;
public class FirstLastDemo { public static void main(String[] args) { List<Integer> upiDebits = new ArrayList<>(List.of(120, 45, 999, 60, 310));
// before Java 21 int firstOld = upiDebits.get(0); int lastOld = upiDebits.get(upiDebits.size() - 1); System.out.println("Old way: first " + firstOld + ", last " + lastOld);
// Java 21 System.out.println("New way: first " + upiDebits.getFirst() + ", last " + upiDebits.getLast());
System.out.print("Newest first:"); for (int amount : upiDebits.reversed()) { System.out.print(" " + amount); } System.out.println(); }}Old way: first 120, last 310 New way: first 120, last 310 Newest first: 310 60 999 45 120
What this code does
getFirst()andgetLast()replaceget(0)andget(size() - 1): no index maths, no chance of an off-by-one.reversed()lets a normal for-each loop walk the list from the end, so a backwards index loop is not needed.
With Java 21 you write list.getLast(). It says what you mean, and list.getFirst() matches it at the other end. To walk a list from the end, use for (var x : list.reversed()) instead of a backwards index loop. On an empty collection, getFirst() and getLast() throw NoSuchElementException, the same as a deque. Check isEmpty() first when the collection can be empty.
LinkedHashSet and LinkedHashMap gain a defined first and last
A LinkedHashSet keeps elements in the order they were added. That order always existed, but there was no direct way to ask for the first or last element. Now it is a SequencedSet, so getFirst(), getLast() and reversed() just work.
Example 3 · LinkedHashSet: first, last and moving to the front
// Java 21import java.util.LinkedHashSet;import java.util.List;import java.util.SequencedSet;
public class RecentSearchDemo { public static void main(String[] args) { SequencedSet<String> recent = new LinkedHashSet<>(); for (String q : List.of("java records", "dsa sheet", "upi limit", "dsa sheet")) { recent.add(q); } System.out.println("In first-search order: " + recent); System.out.println("Oldest: " + recent.getFirst() + " | newest: " + recent.getLast());
recent.addFirst("upi limit"); System.out.println("After addFirst(\"upi limit\"): " + recent);
System.out.println("Reversed view: " + recent.reversed()); recent.removeLast(); System.out.println("After removeLast: " + recent); }}In first-search order: [java records, dsa sheet, upi limit]
Oldest: java records | newest: upi limit
After addFirst("upi limit"): [upi limit, java records, dsa sheet]
Reversed view: [dsa sheet, java records, upi limit]
After removeLast: [upi limit, java records]What this code does
- A
LinkedHashSetkeeps unique items in the order they were first added, so the repeated"dsa sheet"is ignored. Java 21 addsgetFirst()andgetLast(), which earlier needed an iterator loop. - In a
LinkedHashSet,addFirstmoves an existing element to the front instead of adding a copy. That is exactly the behaviour a "recent searches" list needs.
In a LinkedHashSet, addFirst(e) puts e at the front, and moves it there if it was already present.
LinkedHashMap became a SequencedMap in the same way. TreeSet and TreeMap are sequenced too, ordered by their sort order, but they cannot accept addFirst or putFirst: the sort order decides positions, so those calls throw UnsupportedOperationException.
HashSet and HashMap have no defined order, so they are not sequenced. Calling getFirst() on a HashSet is a compile error.
Java 21: SequencedMap
A SequencedMap is a map with an order on its keys. It adds methods to reach the entries at both ends. Each entry is a Map.Entry, with getKey() and getValue().
Example 4 · SequencedMap: first and last entries
// Java 21import java.util.LinkedHashMap;import java.util.Map;import java.util.SequencedMap;import java.util.TreeMap;
public class WaitingListDemo { public static void main(String[] args) { SequencedMap<String, Integer> waiting = new LinkedHashMap<>(); waiting.put("Rohit", 2); waiting.put("Sana", 4); waiting.put("Ajay", 3); System.out.println("Waiting list: " + waiting); System.out.println("First: " + waiting.firstEntry() + ", last: " + waiting.lastEntry());
waiting.putFirst("Dr. Mehta (VIP)", 1); Map.Entry<String, Integer> next = waiting.pollFirstEntry(); System.out.println("Seated: " + next.getKey() + ", table for " + next.getValue()); System.out.println("Left the queue: " + waiting.pollLastEntry()); System.out.println("Now: " + waiting + ", reversed: " + waiting.reversed());
TreeMap<Integer, String> rankList = new TreeMap<>(Map.of(3, "Kiran", 1, "Anu", 2, "Zaid")); System.out.println("Rank 1: " + rankList.firstEntry().getValue() + ", last rank: " + rankList.lastEntry()); }}Waiting list: {Rohit=2, Sana=4, Ajay=3}
First: Rohit=2, last: Ajay=3
Seated: Dr. Mehta (VIP), table for 1
Left the queue: Ajay=3
Now: {Rohit=2, Sana=4}, reversed: {Sana=4, Rohit=2}
Rank 1: Anu, last rank: 3=KiranWhat this code does
- A
LinkedHashMapkeeps keys in insertion order, and as aSequencedMapit can read, remove and insert at both ends.putFirstjumps the VIP to the front;pollFirstEntryremoves and returns that entry. - A
TreeMapis sequenced by key order, sofirstEntry()is the smallest key. It already had these methods throughNavigableMap; Java 21 makes them part of the sharedSequencedMapinterface.
firstEntry()/lastEntry(): read the entry at either end, ornullif empty.pollFirstEntry()/pollLastEntry(): remove and return it.putFirst(k, v)/putLast(k, v): insert or move a key to an end (LinkedHashMap).reversed(),sequencedKeySet(),sequencedValues(),sequencedEntrySet(): ordered views.
pollFirstEntry() and pollLastEntry() remove and return an end entry, which is handy for processing items in the order they arrived, like a waiting list. On an empty map, the entry methods return null instead of throwing.
Example 5 · Traps: empty, unmodifiable and sorted collections
// Java 21import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.TreeSet;
public class SequencedTrapsDemo { public static void main(String[] args) { List<String> empty = new ArrayList<>(); try { empty.getFirst(); } catch (Exception e) { System.out.println("getFirst on empty list: " + e.getClass().getSimpleName()); } try { empty.get(0); } catch (Exception e) { System.out.println("get(0) on empty list: " + e.getClass().getSimpleName()); }
List<String> fixed = List.of("Mon", "Tue"); System.out.println("List.of getLast: " + fixed.getLast()); try { fixed.addFirst("Sun"); } catch (Exception e) { System.out.println("List.of addFirst: " + e.getClass().getSimpleName()); }
TreeSet<Integer> sorted = new TreeSet<>(List.of(40, 10, 30)); System.out.println("TreeSet first/last: " + sorted.getFirst() + "/" + sorted.getLast()); try { sorted.addFirst(99); } catch (Exception e) { System.out.println("TreeSet addFirst: " + e.getClass().getSimpleName()); }
System.out.println("Empty map firstEntry: " + new LinkedHashMap<String, Integer>().firstEntry()); }}getFirst on empty list: NoSuchElementException get(0) on empty list: IndexOutOfBoundsException List.of getLast: Tue List.of addFirst: UnsupportedOperationException TreeSet first/last: 10/40 TreeSet addFirst: UnsupportedOperationException Empty map firstEntry: null
What this code does
- On an empty list,
getFirst()throwsNoSuchElementException, whileget(0)throwsIndexOutOfBoundsException. An empty map'sfirstEntry()returnsnullinstead. - Reading the ends always works, but adding needs a modifiable collection whose order you control.
List.ofcannot change, and aTreeSetdecides positions by sorting, so both throwUnsupportedOperationException.
Next step
Check your understanding
12 quick questions