Sub topic 1
Java Sequenced Collections: Working with First, Last and Reversed Order
Prerequisites
This chapter assumes Java 21 or newer, familiarity with List, Set, Map, and Deque, and an understanding of ordered versus sorted collections.
Why first and last were awkward before Java 21
Before Java 21, collection classes used different methods for the same idea. A list used index arithmetic:
String first = names.get(0);
String last = names.get(names.size() - 1);A deque used peekFirst() and peekLast() for safe reads, or getFirst() and getLast() for reads that throw when empty. A linked hash set had no direct first-or-last methods. You had to use an iterator, convert the set, or maintain extra logic.
These differences made generic methods harder to write. A method accepting List<String> could not also accept every ordered set or deque.
What encounter order means
Encounter order is the order in which a collection's iterator visits its elements. An ArrayList preserves insertion order. A LinkedHashSet preserves its defined insertion order while removing duplicates. A TreeSet uses comparator order. A HashSet has no guaranteed encounter order.
Sequenced interfaces apply only when a collection has a meaningful first and last element.
SequencedCollection: one API for both ends
Java 21 added SequencedCollection. Lists, deques, and ordered sets can expose:
getFirst()andgetLast()to read elementsaddFirst()andaddLast()to insert or reposition elementsremoveFirst()andremoveLast()to remove elementsreversed()to obtain reverse encounter order
The interface lets a method describe the behavior it needs instead of requiring a particular implementation.
import java.util.ArrayList;
import java.util.List;
public class Ends {
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("b", "c", "d"));
names.addFirst("a");
names.addLast("e");
System.out.println(names.getFirst()); // a
System.out.println(names.getLast()); // e
}
}Reversed views: iterating backwards and write-through behavior
reversed() returns a live view, not a copied collection. Iterating or streaming the view visits elements from last to first. Changes made through either reference are visible through the other.
import java.util.ArrayList;
import java.util.List;
public class ReverseView {
public static void main(String[] args) {
List<Integer> values = new ArrayList<>(List.of(1, 2, 3));
List<Integer> reverse = values.reversed();
reverse.add(0);
values.add(4);
System.out.println(values); // [0, 1, 2, 3, 4]
System.out.println(reverse); // [4, 3, 2, 1, 0]
}
}Exercise
Why is reversed() preferable to copying a list and calling Collections.reverse() when you need a changing reverse view?
Show answer
It stays connected to the original collection, so later changes remain visible in both directions.