Java / Java 21 Collection Framework features Interview questions
What is the purpose of the reversed() method in Java 21 collections?
reversed() gives you a view of a sequenced collection with its encounter order flipped, without copying any elements or building a new backing structure.
Because it's a view, changes made through the reversed collection are reflected in the original, and changes to the original show up when you read through the reversed view - they share the same underlying data.
List<Integer> nums = new ArrayList<>(List.of(1, 2, 3)); List<Integer> rev = nums.reversed(); // [3, 2, 1] nums.add(4); System.out.println(rev); // [4, 3, 2, 1]
This replaces one-off uses of Collections.reverse() or manual index loops when all you need is to read or iterate a collection back-to-front.
More Related questions...