Java / Java 21 Collection Framework features Interview questions
How can you optimize iteration and access using SequencedCollection methods instead of manual indexing?
Using getFirst()/getLast() instead of manual index math doesn't change the algorithmic complexity for something like ArrayList - both are O(1) - but it does eliminate an entire class of off-by-one bugs from re-deriving size() - 1 everywhere.
The bigger optimization opportunity is on collections where manual "reverse iteration" used to be genuinely expensive: reversing a LinkedHashSet before Java 21 typically meant copying every element into a List first, an O(n) operation with extra memory allocation. Calling .reversed() now avoids that copy entirely, since it's a constant-time view.
// Before: O(n) copy just to iterate backward List<String> copy = new ArrayList<>(linkedHashSet); Collections.reverse(copy); // Java 21: O(1) view, no copy for (String s : linkedHashSet.reversed()) { /* ... */ }
So the real win is avoiding unnecessary copies and allocations in reverse-iteration and end-access code paths, not making index-based access itself faster.
More Related questions...