List.reversed()
Returns the list in reverse order without copying it.
Available since: Java 21
Syntax
default List<E> reversed()Return value
List<E>A reverse-ordered view of the list.
Examples
Iterating from the end:
void main() {
List<Integer> nums = List.of(1, 2, 3, 4);
for (int n : nums.reversed()) {
IO.print(n + " ");
}
IO.println("");
}Output:
4 3 2 1The view is linked to the original list:
void main() {
List<String> list = new ArrayList<>(List.of("a", "b"));
List<String> back = list.reversed();
list.add("c");
IO.println(back);
}Output:
[c, b, a]Notes
The method comes from SequencedCollection (Java 21); it also exists on Deque, LinkedHashSet and TreeSet, while LinkedHashMap and TreeMap have their own reversed(). Unlike Collections.reverse(), the original list is not changed.
See also
- Collections.reverse() — Reverses the order of list elements in place.
- List.getFirst() — Returns the first or the last element of an ordered collection.
- List.sort() — Sorts a list in place using a given rule.
Related recipes
In the tutorial
- Lists: List and ArrayList — Lists in Java: ArrayList, adding, reading and removing elements, unmodifiable List.of lists and lists of numbers.