Sub topic 1
Why First and Last Were Awkward Before Java 21
Prerequisites
You should know the basic List, Set, Map, and Deque interfaces. You should also understand the difference between an ordered collection, a sorted collection, and an unordered collection. The examples use Java 17-style collection APIs, before the sequenced collection interfaces were added.
The missing common vocabulary
Many collections have a meaningful order. That order is called the encounter order. It is the order in which an iterator visits elements.
An ArrayList has an encounter order based on its indexes. A LinkedHashSet keeps insertion order. A TreeSet uses its comparator or natural ordering. A HashSet does not promise a useful encounter order.
Before Java 21, the collection interfaces did not provide one common way to ask for the first or last element. Each collection type used a different idiom:
| Collection | First element before Java 21 | Last element before Java 21 |
|---|---|---|
| `List` | `list.get(0)` | `list.get(list.size() - 1)` |
| `Deque` | `deque.getFirst()` | `deque.getLast()` |
| `TreeSet` | `set.first()` | `set.last()` |
| `LinkedHashSet` | `set.iterator().next()` | Iterate through all elements |
This made generic code harder to write. A method that worked with a List could not automatically accept a Set, even when both collections had a defined encounter order.
Lists and deques used different styles
A list exposes positions. To read its ends, code used index arithmetic:
import java.util.ArrayList;
import java.util.List;
public class LegacyListEnds {
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("Ada", "Lin", "Mina"));
String first = names.get(0);
String last = names.get(names.size() - 1);
System.out.println(first); // Ada
System.out.println(last); // Mina
}
}The expression names.size() - 1 is easy to get wrong. It also fails when the list is empty. Calling get(0) or get(size - 1) on an empty list throws IndexOutOfBoundsException.
A Deque already had end-oriented methods. getFirst() and getLast() describe the operation directly. However, those methods belonged to Deque, not to the general Collection or List interfaces. The API depended on the variable's declared type and the collection's role.
Sets required more assumptions
A TreeSet had first() and last() because its sorted order defined both ends. A LinkedHashSet preserved insertion order but did not have matching methods before Java 21.
To find the first element of a LinkedHashSet, code commonly created an iterator:
import java.util.LinkedHashSet;
import java.util.Set;
public class LegacySetEnds {
public static void main(String[] args) {
Set<String> colors = new LinkedHashSet<>();
colors.add("red");
colors.add("green");
colors.add("blue");
String first = colors.iterator().next();
String last = null;
for (String color : colors) {
last = color;
}
System.out.println(first); // red
System.out.println(last); // blue
}
}This code assumes that the set has a stable encounter order. It also needs special handling for an empty set. Calling next() when the iterator has no element throws NoSuchElementException. Finding the last element requires visiting every element.
An ordinary HashSet makes these operations meaningless as an ordering feature. Its iterator may return elements in an order that changes after modifications or across implementations.
Maps had another set of idioms
A map stores key-value entries rather than standalone elements. Before Java 21, Map had no general firstEntry() or lastEntry() operation.
For a LinkedHashMap, code could inspect its entry iterator:
import java.util.LinkedHashMap;
import java.util.Map;
public class LegacyMapEnds {
public static void main(String[] args) {
Map<String, Integer> scores = new LinkedHashMap<>();
scores.put("Ada", 10);
scores.put("Lin", 20);
scores.put("Mina", 30);
Map.Entry<String, Integer> first =
scores.entrySet().iterator().next();
Map.Entry<String, Integer> last = null;
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
last = entry;
}
System.out.println(first); // Ada=10
System.out.println(last); // Mina=30
}
}A TreeMap had sorted-map methods such as firstEntry() and lastEntry(), but those methods were not shared by every map with a defined encounter order. The distinction between insertion order and sorted order also remained important.
Why this mattered
The problem was not that Java lacked ways to access ends. The problem was that related collections exposed unrelated APIs. Generic library code had to choose a narrow parameter type, use instanceof, or duplicate logic for lists, deques, linked collections, and sorted collections.
Java 21 introduced interfaces that describe a collection's encounter order directly. These interfaces provide common first, last, and reversed-order operations while preserving the existing differences between insertion-ordered, sorted, and unordered collections.
Exercise
Why is set.iterator().next() an unsafe replacement for a general “first element” operation?
Show answer
It assumes that the set has a defined encounter order and that it is not empty. An unordered set has no stable first element, and an empty set causes next() to throw NoSuchElementException.