Reverse a List in Java

We can reverse a List in Java in the following ways:

  • Using the Collections.reverse() method
  • Using List.add() and List.remove() methods
  • Using the for-loop

Reverse a List in Java using the Collections.reverse() method

The Collections class from java.util package has a static method reverse() that we can use to reverse the order of elements in the specified list.

Example

public class Test {z

  public static void main(String[] args) {

    List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));

    Collections.reverse(numbers);

    System.out.println(numbers);
  }
}
Output: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

Reverse a List using List.add() and List.remove() methods

We can use the add(int index, E element) method to reverse a list. We provide an index of the element as the first argument, and as the second argument, we will put the remove(int index), which removes the element and returns it.

The add() method is part of the Java Collection Framework. It is a member of the List interface and is inherited by classes such as ArrayList, LinkedList, Vector, etc.

Example

public class Test {

  public static void main(String[] args) {

    List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));

    for (int k = 0, j = numbers.size() - 1; k < j; k++) {
      numbers.add(k, numbers.remove(j));
    }

    System.out.println(numbers);
  }
}
Output: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

Reverse a List using the for-loop

There is also a way to reverse a list by creating a new list and adding all the elements from the original list in reverse order.

Example

public class Test {

  public static void main(String[] args) {

    List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));

    List<Integer> reversedNumbers = new ArrayList<>();

    // iterate over the list in reverse order
    for (int i = numbers.size() - 1; i >= 0; i--) {
      reversedNumbers.add(numbers.get(i));
    }

    System.out.println(reversedNumbers);
  }
}
Output: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
 
That’s it!

Leave a Reply

Your email address will not be published. Required fields are marked *