SequencedCollection gives an encounter-ordered collection endpoint operations and a reversed view without requiring indexed access.
Java 21 sequenced collections: endpoints and reversed views
Java 21+. This is a complete program using JDK classes.
Name the encounter order
A route trace needs a first stage and a last stage. Prior to the sequenced interfaces, that requirement was expressed differently for lists and ordered sets. The interface now names those operations for collections that have a defined encounter order.
Reversed means a view with the opposite order, not a detached copy. Updating a mutable original can affect the view. Make a separate copy when handing out a snapshot, and check whether the underlying collection permits an endpoint update before assuming every implementation behaves like ArrayList.
Order can come from insertion, access, or sorting. A sorted set may not permit an arbitrary addFirst because that would conflict with its ordering rule. Choose the implementation by the order your application needs; the shared interface does not erase implementation restrictions.
Keep the toolchain honest
The example compiles for Java 21. Changing only a project label does not add these methods to Java 8 or 17. Library consumers also need a runtime that supports the compiled API usage, so version labels belong next to the program and in the build configuration.
Working program
import java.util.ArrayList;
import java.util.List;
import java.util.SequencedCollection;
public class ReversedRouteView {
public static void main(String[] args) {
SequencedCollection<String> stages = new ArrayList<>(List.of("received", "packed"));
SequencedCollection<String> reverse = stages.reversed();
System.out.println(stages.getFirst());
System.out.println(reverse);
stages.addLast("dispatched");
System.out.println(reverse);
System.out.println(reverse.getFirst());
}
}Output
received
[packed, received]
[dispatched, packed, received]
dispatchedCosts and boundaries
This ArrayList-backed view does not duplicate every element to reverse its traversal. Full traversal remains O(n), and endpoint insertion costs follow the underlying collection. For example, inserting at the front of an array-backed list can shift O(n) references.
Common Mistakes
- A reversed view is not a snapshot.
- The interface does not promise that every endpoint update is supported.
- Do not put Java 21 calls in a Java 8-labelled sample.
