Learnitweb

Reverse a List in Java

Assume a List<T> list:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);

Approach 1: Using Streams (Index-based mapping)

List<Integer> reversed = IntStream.range(0, list.size())
    .mapToObj(i -> list.get(list.size() - 1 - i))
    .collect(Collectors.toList());

Approach 2: Using Collections.reverse() (Recommended for mutable lists)

List<Integer> copy = new ArrayList<>(list); // create a copy if original should stay unchanged
Collections.reverse(copy);