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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
