Programming for fun and profit

Programming tutorials, problems, solutions. Always with code.

Java reverse List


How to reverse Java List when List doesn’t have such method? As usually the solution is in Java Collections API.


The following simple Java example shows how to use Collections.reverse(List) from vast java.util package:


import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class CollectionsReverse {

    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4);
        System.out.println("Numbers: " + numbers);

        System.out.println("Reversed: " + numbers);

Unlike in functional languages, the operation reorders given List and doesn’t return a new one. Reordering runs in linear time.

Keep in mind that if may throw UnsupportedOperationException when List implementation (or their iterator) doesn’t support set operation.

The result of the running the Java example:

Numbers: [1, 2, 3, 4]
Reversed: [4, 3, 2, 1]
Share with the World!