Java / Java 21 Collection Framework features Interview questions
What are getFirst() and getLast() used for?
getFirst() and getLast() return the first and last elements of a sequenced collection according to its encounter order, without removing them.
On a List, they're equivalent to list.get(0) and list.get(list.size() - 1), but they read more clearly and work the same way across every sequenced type, including sets and deques.
Deque<String> queue = new ArrayDeque<>(List.of("A", "B", "C")); System.out.println(queue.getFirst()); // A System.out.println(queue.getLast()); // C
Both throw NoSuchElementException if the collection is empty, so it's worth checking isEmpty() first when the collection might have no elements.
More Related questions...