Java / Java 21 Collection Framework features Interview questions
What are removeFirst() and removeLast() used for?
removeFirst() removes and returns the first element of a sequenced collection, while removeLast() does the same for the last element, shrinking the collection by one.
They combine the read-and-remove step into a single call, which is convenient for stack- and queue-style processing where you repeatedly consume from one end.
Deque<Integer> stack = new ArrayDeque<>(List.of(1, 2, 3)); int top = stack.removeFirst(); // 1, stack is now [2, 3]
Both throw NoSuchElementException on an empty collection, so code that loops until empty typically checks isEmpty() before calling either.
More Related questions...