Java / Java 21 Interview Questions
What are Sequenced Collections in Java 21?
JEP 431 introduces three new interfaces — SequencedCollection, SequencedSet, and SequencedMap — to the collections hierarchy. Before Java 21 there was no unified API to access the first or last element of a collection, or to iterate in reverse order; each concrete class had its own ad-hoc approach.
| Collection | Get first | Get last | Reverse iteration |
|---|---|---|---|
| List | list.get(0) | list.get(list.size()-1) | Collections.reverse() / listIterator |
| Deque | deque.peekFirst() | deque.peekLast() | descendingIterator() |
| SortedSet | sortedSet.first() | sortedSet.last() | No standard way |
| LinkedHashSet | iter.next() hack | No direct way | No standard way |
// SequencedCollection adds:
interface SequencedCollection extends Collection {
void addFirst(E e);
void addLast(E e);
E getFirst(); // replaces get(0) / peekFirst()
E getLast(); // replaces get(size-1) / peekLast()
E removeFirst();
E removeLast();
SequencedCollection reversed(); // reversed VIEW
}
// Now works uniformly on List, Deque, LinkedHashSet...
List list = new ArrayList<>(List.of("a", "b", "c"));
System.out.println(list.getFirst()); // "a"
System.out.println(list.getLast()); // "c"
list.addFirst("z"); // ["z", "a", "b", "c"]
for (String s : list.reversed()) {
System.out.print(s + " "); // c b a z
}
// SequencedMap adds firstEntry(), lastEntry(), reversed()
SequencedMap map = new LinkedHashMap<>();
map.put("one", 1); map.put("two", 2); map.put("three", 3);
System.out.println(map.firstEntry()); // one=1
System.out.println(map.lastEntry()); // three=3 The reversed() method returns a view — it does not copy the collection. Modifications through the reversed view affect the backing collection. All List, Deque, SortedSet, LinkedHashSet, SortedMap, and LinkedHashMap implementations now implement the appropriate sequenced interface.
More Related questions...