Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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 1

The 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

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.

Thanks for reading!

Donate to the site — we work hard for you.