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.
import java.util.*;
class Main {
public static void main(String[] args) {
//Initialize the list with values
List<Integer> ids = Arrays.asList(1, 2, 3, 4, 5);
//Pass the list as an argument to reverse it
Collections.reverse(ids);
//Output the revresed list
System.out.println(ids);
}
}
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.
import java.util.*;
class Main {
public static void main(String[] args) {
//Initialize the list
List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
//Call the reverse funtion
reverseList(numbers);
//Print the revresed list
System.out.println(numbers);
}
//Generic recursive funtion to reverse a list
public static<T> void reverseList(List<T> list){
//Base condition - return if list is empty or null
if(list==null || list.size()==0){
return;
}
//Pop the first items
T item = list.remove(0);
//Recursive call
reverseList(list);
//append the item at the back of the list
list.add(item);
}
}
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:
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.
import java.util.*;
class Main {
public static void main(String[] args) {
//Initiale the list with values
List<Character> alpha = Arrays.asList('a', 'b', 'c', 'd', 'e');
//call the revreseList() method
List<Character> reverse_alpha = reverseList(alpha);
//Output the new
System.out.println(reverse_alpha);
}
//Generic method returns the reverse of the list
private static<T> List<T> reverseList(List<T> list){
//Create another list to store elements in reverse order
List<T> reverse = new ArrayList<>(list.size());
//Iterate through input list in revese order
for(int i=list.size()-1; i>=0; i--){
//add item to the new list
reverse.add(list.get(i));
}
//Return the revresed list
return reverse;
}
}
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:
- Loop from
0
tolist.size()-1
. - Pop item from the front i.e.
item = list.remove(0)
. - Append
item
at the end i.e.list.add(item)
.
Here is the implementation of the steps in Java:
import java.util.*;
class Main {
public static void main(String[] args) {
//Initiale the list with values
List<Character> alpha = new ArrayList<>(Arrays.asList('a', 'b', 'c', 'd', 'e'));
//call the revreseList() method
reverseList(alpha);
//Output the new
System.out.println(alpha);
}
//Generic method revrese the list passed as argument
private static<T> void reverseList(List<T> list){
for(int i=0; i<list.size(); i++){
//Pop from front & Append to the last
list.add(list.remove(0));
}
}
}
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.