Sub topic 1
Why first and last were awkward before Java 21
Reading the first or last element of a collection is one of the most common things Java programs do. Before Java 21, no single method name worked across the collection types that have a defined order. This chapter shows what each type offered, where the gaps were, and why those gaps motivated SequencedCollection, SequencedSet and SequencedMap.
Prerequisites
This chapter assumes you already know:
- The core
java.utiltypes:List,Set,MapandDeque. - The difference between ordered, sorted and unordered collections.
ArrayListandLinkedHashSetkeep an order,TreeSetsorts, andHashSetguarantees nothing. - Basic generics and interfaces with default methods.
- How to compile and run a single-file Java program. The examples in this chapter run on any JDK from 16 onward, because they use pattern matching for
instanceof.
The problem in one sentence
Several collections have a first and a last element, but each type exposed them through a different method, and some types exposed only one end or neither.
Take a plain question: "What is the last element?" The answer depended on the static type of the variable.
import java.util.*;
public class LastElementTour {
public static void main(String[] args) {
List<String> list = new ArrayList<>(List.of("a", "b", "c"));
Deque<String> deque = new ArrayDeque<>(List.of("x", "y", "z"));
SortedSet<Integer> sorted = new TreeSet<>(List.of(5, 1, 9));
NavigableMap<String, Integer> navMap = new TreeMap<>(Map.of("k1", 1, "k2", 2));
System.out.println(list.get(list.size() - 1)); // c
System.out.println(deque.getLast()); // z
System.out.println(sorted.last()); // 9
System.out.println(navMap.lastEntry()); // k2=2
}
}Four types, four spellings. None of these methods is wrong. The trouble is that they share no supertype, so code written against one cannot be reused for another.
First and last element access by type
The table lists what the JDK offered before Java 21.
| Type | First element | Last element | On an empty collection |
|---|---|---|---|
| `List` | `get(0)` | `get(size() - 1)` | `IndexOutOfBoundsException` |
| `Deque` | `getFirst()` or `peekFirst()` | `getLast()` or `peekLast()` | `NoSuchElementException` or `null` |
| `SortedSet`, `NavigableSet` | `first()` | `last()` | `NoSuchElementException` |
| `LinkedHashSet` | `iterator().next()` | iterate through every element | `NoSuchElementException` from `next()` |
| `SortedMap` | `firstKey()` | `lastKey()` | `NoSuchElementException` |
| `NavigableMap` | `firstEntry()` | `lastEntry()` | `null` |
| `LinkedHashMap` | `entrySet().iterator().next()` | iterate through every entry | `NoSuchElementException` from `next()` |
Three problems show up in this table.
- Inconsistent names. The same idea is
get(0),getFirst(),first(),firstKey(),firstEntry()or an iterator call. - Inconsistent failure. Asking for an element of an empty collection throws one of two exceptions or returns
null, depending on the type and sometimes on the method. - Missing operations.
LinkedHashSetandLinkedHashMaphave a well-defined order, yet they had no direct way to read the last element.
Index arithmetic on lists
For a List, the last element needed list.get(list.size() - 1). The expression works, but it has two weak points. It names the variable twice, which is awkward when the list comes from a method call, as in compute().get(compute().size() - 1). That form calls compute() twice, so you must store the result in a local variable first.
It also fails in a confusing way on an empty list.
import java.util.ArrayList;
import java.util.List;
public class EmptyListLast {
public static void main(String[] args) {
List<String> empty = new ArrayList<>();
try {
String last = empty.get(empty.size() - 1);
System.out.println(last);
} catch (IndexOutOfBoundsException e) {
System.out.println(e.getMessage()); // Index -1 out of bounds for length 0
}
}
}The message reports index -1, which is an artifact of your arithmetic. It does not say "the list is empty".
Two sets of operations on deques
Deque is the one interface that treated both ends symmetrically. It has addFirst, addLast, removeFirst, removeLast, getFirst, getLast, plus peek and poll variants that return null or false instead of throwing. But Deque is a queue-like type. ArrayList is not a Deque, and neither is LinkedHashSet. LinkedList implements both List and Deque, so it was the only common class with both vocabularies.
Sorted types have their own words
SortedSet has first() and last(). NavigableSet adds pollFirst() and pollLast(). TreeMap offers firstKey() and firstEntry(), which differ in how they treat an empty map. firstKey() throws NoSuchElementException, while firstEntry() returns null. These names exist because sorted collections predate Deque, and each interface was designed in isolation.
Linked hash collections had no answer at all
LinkedHashSet and LinkedHashMap keep elements in insertion order. They are the standard way to get a set or map that remembers order. Yet reading the first element meant creating an iterator, and reading the last meant walking the whole collection.
import java.util.LinkedHashSet;
import java.util.NoSuchElementException;
import java.util.Set;
public class LinkedHashSetLegacy {
public static void main(String[] args) {
Set<String> set = new LinkedHashSet<>();
set.add("p");
set.add("q");
set.add("r");
String first = set.iterator().next();
System.out.println(first); // p
String last = null;
for (String s : set) {
last = s; // visits every element
}
System.out.println(last); // r
Set<String> empty = new LinkedHashSet<>();
try {
empty.iterator().next();
} catch (NoSuchElementException e) {
System.out.println("empty set: next() threw");
}
}
}Finding the last element takes time proportional to the size of the set. Some programmers copied the set into an ArrayList just to call get(size - 1), which also copies every element.
Generic code could not ask for "the first element"
The most damaging gap is not about syntax. Collection has no getFirst(), because a HashSet has no meaningful first element. A method that accepts Collection<T> therefore had to inspect the runtime type.
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Deque;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
public class LegacyLast {
static <T> T lastOf(Collection<T> c) {
if (c instanceof List<T> list) {
return list.get(list.size() - 1);
}
if (c instanceof Deque<T> deque) {
return deque.getLast();
}
if (c instanceof SortedSet<T> sorted) {
return sorted.last();
}
T last = null;
boolean found = false;
for (T t : c) {
last = t;
found = true;
}
if (!found) {
throw new NoSuchElementException();
}
return last;
}
public static void main(String[] args) {
System.out.println(lastOf(List.of("a", "b", "c"))); // c
System.out.println(lastOf(new ArrayDeque<>(List.of("x", "y")))); // y
System.out.println(lastOf(new TreeSet<>(List.of(5, 1, 9)))); // 9
Set<String> linked = new LinkedHashSet<>(List.of("p", "q", "r"));
System.out.println(lastOf(linked)); // r
}
}This helper has real defects.
- It must be updated whenever a new ordered type appears.
- The final loop also accepts a
HashSet, where the "last" element is arbitrary. The code compiles and returns a value, so the mistake goes unnoticed. - Each branch fails differently on an empty input. The
Listbranch throwsIndexOutOfBoundsException, and the others throwNoSuchElementException.
Reverse iteration was equally scattered
Reading elements from the end backwards had the same problem. Each type had its own idiom, and several had none.
| Type | Reverse traversal before Java 21 |
|---|---|
| `List` | `listIterator(size())` with `hasPrevious()` and `previous()`, or copy and `Collections.reverse` |
| `Deque` | `descendingIterator()` |
| `NavigableSet` | `descendingSet()` or `descendingIterator()` |
| `NavigableMap` | `descendingMap()`, `descendingKeySet()` |
| `LinkedHashSet`, `LinkedHashMap` | copy into a list and reverse the copy |
The next example shows all three families side by side.
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.NavigableSet;
import java.util.Set;
import java.util.TreeSet;
public class LegacyReverse {
public static void main(String[] args) {
List<String> list = new ArrayList<>(List.of("a", "b", "c"));
ListIterator<String> it = list.listIterator(list.size());
while (it.hasPrevious()) {
System.out.print(it.previous() + " "); // c b a
}
System.out.println();
Deque<String> deque = new ArrayDeque<>(List.of("x", "y", "z"));
Iterator<String> desc = deque.descendingIterator();
while (desc.hasNext()) {
System.out.print(desc.next() + " "); // z y x
}
System.out.println();
NavigableSet<Integer> tree = new TreeSet<>(List.of(1, 2, 3));
System.out.println(tree.descendingSet()); // [3, 2, 1]
Set<String> linked = new LinkedHashSet<>(List.of("p", "q", "r"));
List<String> copy = new ArrayList<>(linked);
Collections.reverse(copy);
System.out.println(copy); // [r, q, p]
}
}Two points are easy to miss.
Collections.reverse(list)reverses the list in place. It changes your data, and it cannot be applied to an unmodifiable list. The nameCollections.reverseOrder()is unrelated: it returns aComparator, not a reversed collection.- Streams offered no reverse operation either. To stream a
LinkedHashSetbackwards you had to copy it first, becauseStreamhas noreversed()step.
A related trap: two stack conventions
The lack of a shared vocabulary also made direction itself ambiguous. The legacy java.util.Stack class extends Vector, so push appends to the end and iteration runs from bottom to top. A Deque used as a stack inserts at the front with push, so iteration runs from top to bottom. The two classes hold the same logical contents, but a for loop over each visits the elements in opposite orders.
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Stack;
public class TwoStacks {
public static void main(String[] args) {
Stack<Integer> legacy = new Stack<>();
Deque<Integer> modern = new ArrayDeque<>();
for (int i = 1; i <= 3; i++) {
legacy.push(i);
modern.push(i);
}
System.out.println(legacy); // [1, 2, 3]
System.out.println(modern); // [3, 2, 1]
}
}Without a common interface that says "this collection has a first and last element", code cannot even express which end it means.
What Java 21 changes
Java 21 introduces the interfaces SequencedCollection, SequencedSet and SequencedMap (JEP 431). They give every collection with a defined order the same methods for both ends and for reverse order. The same lookup that took four idioms above becomes one call.
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.TreeSet;
public class AfterJava21 {
public static void main(String[] args) {
System.out.println(new ArrayList<>(List.of("a", "b", "c")).getLast()); // c
System.out.println(new ArrayDeque<>(List.of("x", "y")).getLast()); // y
System.out.println(new TreeSet<>(List.of(5, 1, 9)).getLast()); // 9
System.out.println(new LinkedHashSet<>(List.of("p", "q", "r")).getLast()); // r
}
}This program requires JDK 21 or newer. The following chapters cover what encounter order means, how the new interfaces are defined, and how to adopt them without breaking existing code.
Summary of the gaps
- First and last access had at least six different spellings across
List,Deque,SortedSet,NavigableMapand the linked hash types. - Empty collections caused
IndexOutOfBoundsException,NoSuchElementExceptionornull, depending on the type. LinkedHashSetandLinkedHashMaphad no direct way to read the last element or to iterate in reverse.- No interface expressed "has a defined order", so generic code had to test concrete types or guess.
Exercise
A method takes a Collection<String> and must return its last element. Explain why a loop that keeps the final value seen is unsafe before Java 21, and name one type for which it gives a correct answer and one for which it does not.
Show answer
The loop returns whatever the iterator happens to produce last, and Collection does not promise that this is meaningful. For a LinkedHashSet or an ArrayList it returns the element that is truly last in encounter order. For a HashSet it returns an arbitrary element that can change after a resize or rehash. The compiler cannot distinguish the two cases, because before Java 21 no interface marked the collections that have a defined order.
Exercise
Write the pre-Java 21 expression that reads the last key of a LinkedHashMap<String, Integer> map, and state its running time relative to the map size.
Show answer
One correct form is String last = null; for (String k : map.keySet()) { last = k; }. It visits every key, so its running time is proportional to the number of entries, which is O(n). Copying the keys into a list first, as in new ArrayList<>(map.keySet()), is also O(n) and uses extra memory.
Exercise
The same data is pushed (1, 2, 3 in that order) onto a java.util.Stack and onto an ArrayDeque used as a stack. In what order does printing each one show the elements, and why do they differ?
Show answer
The Stack prints [1, 2, 3] and the ArrayDeque prints [3, 2, 1]. Stack extends Vector, so push appends at the end and iteration runs from bottom to top. ArrayDeque.push inserts at the front, so iteration runs from top to bottom.