Summary: Sometimes the logic of the program demands reversing the list to solve the problem. So in this tutorial, we will learn how to reverse a List in Java in different ways.

Method 1: Reverse List using Collections.reverse()

The reverse() method of Collections class available in java.util package reverses a list passed as an argument.

Output:

[5, 4, 3, 2, 1]

This method reverses a List by modifying the list in-place i.e. it doesn’t require an extra list.

It is the simplest method to reverse a List or ArrayList in Java.

Method 2: Reverse List using Recursion

To reverse a list using recursion, we pop the very first item from the list in each recursive call and re-add them during the traceback process.

Because the traceback happens from the last to the first recursive call, the item gets appended in a reversed manner.

Output:

[5, 4, 3, 2, 1]

The reverseList() is a type-safe method that reverses any type of list passed as an argument (In-Place).

The following picture illustrates the working of the reverseList() recursive function:

Reverse list using recursion

In this method, we have used new ArrayList<>(Arrays.asList()) instead of Arrays.asList(1, 2, 3, 4, 5) to initialize the list with values. It is because ArrayList implements RandomAccess (check this for more details) required by the generics in Java for working with index.

Method 3: Reverse List using for Loop

Using for loop, we can reverse the list using with or without an auxiliary list.

Let’s see an example of both.

Using Another List

Loop through the elements of the list in reverse order and simultaneously add them to another list.

Output:

[e, d, c, b, a]

Without Using Another List

We can reverse the list without using another list by poping the item from the front and attaching it to the end. We iteratively do this for every item on the list.

Steps to reverse the list in Java:

  1. Loop from 0 to list.size()-1.
  2. Pop item from the front i.e. item = list.remove(0).
  3. Append item at the end i.e. list.add(item).

Here is the implementation of the steps in Java:

Output:

[e, d, c, b, a]

Note: Initialize the List using ArrayList otherwise the compiler will throw an error.

In this tutorial, we learned how to reverse a list using Collection.reverse(), recursion, and ‘for’ loop in the Java programming language.

Leave a Reply