Sub topic 12
Adopting Sequenced Collections and Avoiding Compatibility Surprises
This chapter assumes you know List, Set, Map, Deque, Java interfaces, and the difference between ordered and unordered collections. It also assumes you can compile and run code with Java 21 or newer.
Java 21 added SequencedCollection, SequencedSet, and SequencedMap. These interfaces give collections with a defined encounter order a common API for their first element, last element, and reversed view.
Choose the right parameter type
When a method needs to work with any collection that has a meaningful order, accept the most general sequenced interface that provides the operations you need.
import java.util.SequencedCollection;
public class FirstItem {
public static <T> T firstOrNull(SequencedCollection<T> items) {
return items.isEmpty() ? null : items.getFirst();
}
public static void main(String[] args) {
System.out.println(firstOrNull(java.util.List.of("red", "blue")));
}
}Using SequencedCollection avoids tying the method to ArrayList, LinkedList, or another implementation. The caller can pass any compatible implementation.
Use SequencedSet when uniqueness is also required. Use SequencedMap when the data consists of key-value entries and the map has a defined encounter order.
Check your minimum Java version
These interfaces are Java 21 APIs. Code that calls getFirst(), reversed(), or putFirst() cannot compile with an older JDK.
| Situation | Result |
|---|---|
| Compile and run with Java 21 | Sequenced APIs are available |
| Compile with Java 17 | The methods and interfaces are unknown |
| Compile with Java 21, run with Java 17 | The runtime cannot provide the required API |
| Compile and run with Java 21, use `ArrayList` | The list supports the new operations |
Check both the compiler and the runtime in your build system. A project can accidentally use a Java 21 compiler while declaring an older release target, or compile correctly and then run on an older production runtime.
Understand implementation compatibility
Many existing JDK collections were retrofitted to implement the new interfaces. For example:
ArrayListandLinkedListimplementSequencedCollection.LinkedHashSetimplementsSequencedSet.TreeSetimplementsSequencedSet, but its order comes from sorting.LinkedHashMapimplementsSequencedMap.HashSetandHashMapdo not provide a defined encounter order and do not implement these interfaces.
The interface type does not guarantee that every operation is supported. A sorted collection can expose its first and last elements, but it cannot move an element to an arbitrary end without violating its comparator-defined order.
Audit old first and last idioms
Before changing code, search for patterns such as:
list.get(0)list.get(list.size() - 1)deque.peekFirst()deque.peekLast()new ArrayList<>(collection)followed byCollections.reverse(...)map.entrySet().iterator().next()
Replace an idiom only when the new method has the same empty-collection behavior. getFirst() and getLast() throw NoSuchElementException when no element exists. If the old code returned null, use an explicit check or a method such as peekFirst() on a deque.
reversed() returns a live view. It does not make an independent copy. This can improve performance, but it also means that changes through either reference can affect the other.
Avoid unsupported operations
Use read operations when the collection controls its own order. TreeSet supports getFirst() and getLast(), but addFirst() and addLast() throw UnsupportedOperationException.
Read-only wrappers have a similar rule. A sequenced unmodifiable wrapper permits inspection and reversed views, but mutating methods such as removeFirst() or putLast() fail. Test these behaviors when migrating code that previously relied on a particular implementation.
A safe migration process
- Confirm that every build, test, and deployment runtime uses Java 21 or newer.
- Change method parameters to
SequencedCollection,SequencedSet, orSequencedMapwhere the contract requires encounter order. - Replace index arithmetic with
getFirst()andgetLast()only after checking empty-input behavior. - Replace copied reverse-order data with
reversed()only when a live view is acceptable. - Test sorted, linked, empty, and unmodifiable implementations.
- Keep unordered types such as
HashMapandHashSetwhere encounter order is not part of the contract.
Exercise
A method currently accepts List<String> only to print the first and last names. What parameter type should it use, and what exception must the caller consider?
Show answer
It should accept SequencedCollection<String>. The caller must consider that getFirst() and getLast() throw NoSuchElementException for an empty collection.