A list is an interface extended from the “collection” interface. To implement the “list” use the classes like ArrayList, LinkedList, Stack, and Vector. These classes are mainly utilized when dealing with or performing operations on a list like reversal. The reversal of a list is an operation in which the index of the element gets reversed as the element residing at the first index moves to the last index and the last one moves to the first index. Similarly, the second element replaces its position with the second last element. The procedure goes for elements residing at all places in the list.
This guide explains the reversal of a list in Java using the following content:
- What is a List in Java?
- Method 1: Reverse a List Using “Collections.reverse()” Method in Java
- Method 2: Reverse a List Using “add()” and “remove()” Methods in Java
- Method 3: Reverse a List Using Recursion Approach in Java
- Method 4: Reverse a List Using ListIterator Approach in Java
- Method 5: Reverse a List Using the Iteration Method in Java
- Method 6: Reverse a List Using Java 8 Stream API
- How to Reverse a LinkedList in Java?
- How to Reverse an ArrayList in Java?
What is a List in Java?
The “List” does not have a fixed size as their size can grow or shrink according to the values added or removed at run time. They have a dynamic nature and the user can add as many elements as required in a list without generating any bound exceptions. The methods mainly used to add or remove elements from the list are described below.
Add an Element to a List
To insert elements in a List either pass the String data type “value” or specify the index number as well where it is required to insert data. These values are required to be passed as the parameters for the “add()” method as mentioned in the syntax below:
void add(int index, String value)
Remove an Element From a List
To remove an element from a list the “remove()” method needs to be invoked with the List name or object. The index of an element that is required to be removed from a list is passed as the parameter of the “remove()” method. The syntax is shown below:
listName.remove(int index)
Let’s create a dummy list in Java and apply the learned “add()” and “remove()” methods over it:
import java.util.*;//importing Basic Java Utilities
public class javabeat {//Creation of Public Class
public static void main(String args[])
{
List<String> provList = new ArrayList<>();
provList.add(0, "Champion");
provList.add(1, "Capua");
provList.add(2, "Arena");
System.out.println("\nList Items before removal Operation:");
System.out.println(provList);
provList.remove(0);
System.out.println("\nList Items after the removal Operation:");
System.out.println(provList);
}
}
The explanation of the above code block:
- First, all “java” utilities are imported and the class “javabeat” containing the “main” method having no return type is created.
- Next, the “List” having the data type of String is created with the name “provList” using the “ArrayList” class.
- The data is inserted inside the created “provList” list at the index numbers “0”, “1”, and “2” using the “add()” method.
- After the insertion of data, the element residing at the index number “0” is deleted using the “remove()” method.
- In the end, elements of the created list before and after the deletion of an element are displayed on the console window.
The output of a provided code shows the elements residing in the list before and after the deletion operation:
After getting the basic and compulsory knowledge about the List. Now, let’s dive into the Java methods or approaches to reverse a list.
Method 1: Reverse a List Using “Collections.reverse()” Method in Java
The “Collections.reverse()” method is the most popular and easy approach to perform the reversal of the selected list. This method automatically accepts the provided list, performs the conversion or reversal operation, and returns the reversed version of the provided list. Visit the below Java program to practically implement the “Collections.reverse()” method:
import java.util.*;
public class javabeat {//Creation of Public Class
public static void main(String args[])//initializing the main() method
{
List<String> provList = new ArrayList<>();
provList.add(0, "1 - Champion");
provList.add(1, "2 - Capua");
provList.add(2, "3 - Arena");
System.out.println("\nOriginal List Before Reversal Operation:");
System.out.println(provList);
Collections.reverse(provList);
System.out.println("\nList After the Reversal Operation:");
System.out.println(provList);
}
}
The description of the above code is as follows:
- Initially, import the required Java utilities and initialize the “main()” method.
- This method contains the list named “provList” and dummy data is inserted in it via the “add()” method, as explained in the above section.
- Next, the created “provList” is passed as a parameter for the “Collections.reverse()” method. The same “provList” list is then displayed over the console to witness any changes.
The generated output shows that the provided list element has been reversed in Java:
Method 2: Reverse a List Using “add()” and “remove()” Methods in Java
The reversal of a list in Java can be done manually by the utilization of “add()” and “remove()” methods with the “for” loop. The working of this approach is explained below:
Step 1: The “for” loop iterates the list from the bottom and top indexes of the list
Step 2: The “remove()” method removes the element residing at the top index and uses the “add()” method to insert the removed element at the bottom index.
Step 3: After the deletion and insertion, the index from both the top and bottom sides gets increased by a factor and moves towards the center.
Step 3: After that same approach is applied to all remaining indexes until the whole list gets reversed.
The practical code example is shown below:
import java.util.*;//importing Basic Java Utilities
public class javabeat {
public static void main(String args[])//initializing the main() method
{
List<String> provList = new ArrayList<>();
provList.add(0, "Champion - 1");
provList.add(1, "Capua - 2");
provList.add(2, "Arena - 3");
System.out.println("\nOriginal List Before Reversal Operation:");
System.out.println(provList);
int y = provList.size() - 1;
for( int x = 0; x < y; x++){
String tempProvList = provList.remove(y);
provList.add(x, tempProvList);
}
System.out.println("\nModified List After the Reversal Operation: ");
System.out.println(provList);
}
}
The explanation of the above code snippet is as follows:
- First, create a “List” named “provList” containing random elements and display its elements over the console.
- Next, a random variable “y” is declared and initialized as “provList.size() – 1” which points to the last index of the “provList” list.
- Then, the “for” loop is utilized pointing from the top index of the list. It iterates till the top index gets equal to the bottom index “y”.
- Inside the loop, the elements residing at the bottom index “y” get removed using the “remove()” method and the result is stored in “tempProvList”.
- The “tempProvList” is added in the same “provList” list at the starting index “x” via the “add()” method.
- Finally, exit from the “for” loop and display the modified “provList” over the console.
The output after the execution of the above code block shows that the original list has been reversed:
Method 3: Reverse a List Using Recursion Approach in Java
The “Recursion” is an approach that invokes itself after each iteration till the specified condition becomes true. Using this method first the element gets removed from the list and after removal, the function calls itself, and this time the removed data gets inserted inside the list generating the reversal version of a list:
import java.util.*;
public class javabeat {
static void reverseOperation(List<String> generation){
if(generation.size() == 0){
return;
}
else{
String ele = generation.remove(0);
reverseOperation(generation);
generation.add(ele);
}
}
public static void main(String args[])
{
List<String> provList = new ArrayList<>();
provList.add(0, "Champion - 1");
provList.add(1, "Capua - 2");
provList.add(2, "Arena - 3");
System.out.println("\nOriginal List Before Reversal Operation:");
System.out.println(provList);
reverseOperation(provList);
System.out.println("\nModified List After the Reversal Operation: ");
System.out.println(provList);
}
}
The explanation of the above code snippet is as follows:
- First, the function “reverseOperation()” having an argument of String type list named “generation” is created.
- Inside the function, an “if/else” statement is utilized to check if the provided list is empty or not.
- If the list is not empty, the element residing at the top of the list(index number of 0) gets removed from the provided “generation” list. The output is stored in a new variable “ele”.
- Moreover, the modified “generation” list is passed into the “reverseOperation()” function to perform the recursive operation. The removed element from the list is now added to the “generation” list.
- After that, utilize a “main()” method containing the random list “provList” and pass this array as an argument for the created “reverseOperation()” function.
The generated output shows that the original provided list has been reversed:
Method 4: Reverse a List Using ListIterator Approach in Java
The “ListIterator” class in Java allows developers to traverse over the list. This approach contains a couple of methods namely “hasPrevious()” and “previous()” that help to perform the reversal operation over the list. The “hasPrevious()” method tells if any element exists before the currently selected index in the list. The “previous()” method selects and retrieves the element that resides before the currently selected index.
Take a look at the below Java program to reverse a list using ListIterator:
import java.util.*;//importing Basic Java Utilities
public class javabeat {//Creation of Public Class
public static void main(String args[])//initializing the main() method
{
List<String> provList = new ArrayList<>();
provList.add(0, "Champion - 1");
provList.add(1, "Capua - 2");
provList.add(2, "Arena - 3");
System.out.println("\nOriginal List Before Reversal Operation:");
System.out.println("\t" + provList);
List<String> reverseProvList = new ArrayList<>();
ListIterator<String> listIterator = provList.listIterator(provList.size()); while(listIterator.hasPrevious()){ String elemenString = listIterator.previous();
reverseProvList.add(elemenString);
}
System.out.println("\nModified List After the Reversal Operation: ");
System.out.println("\t" + reverseProvList);
}
}
The description of the above code snippet is as follows:
- First, import the required Java utility, create the “main()” method, and inside the method create a List named “provList” which contains data using the “add()” method.
- Also, create a new list named “reverseProvList” using the “ArrayList” class.
- Now, create a String type ListIterator named “listiterator” having a size equal to the “provList” list.
- After that, utilize the “while” loop that checks if there is any preceding index or not. If the condition is true, then the previous item from the list gets selected and added.
The generated output confirms the reversal of the list in Java:
Method 5: Reverse a List Using the Iteration Method in Java
This “iteration” method is the most basic and is easy to understand. This method consists of two lists, the first one contains the original data that is required to be reversed, the other one is empty. The working of this method is simple, the elements from the first list get removed from the bottom side and placed in the secondary empty list. For instance, visit the below code block:
import java.util.*;//importing Basic Java Utilities
public class javabeat {//Creation of Public Class
public static void main(String args[])
{
List<String> provList = new ArrayList<>();
provList.add(0, "Champion - 1");
provList.add(1, "Capua - 2");
provList.add(2, "Arena - 3");
System.out.println("\nOriginal List Before Reversal Operation:");
System.out.println("\t" + provList);
List<String> reverseProvList = new ArrayList<>();
for( int i = provList.size()-1; i >= 0; i--){
String element = provList.get(i);
reverseProvList.add(element);
}
System.out.println("\nModified List After the Reversal Operation: ");
System.out.println("\t" + reverseProvList);
}
}
The above code works like this:
- First, create a targeted list “provList” and insert random values inside it using the “add()” method.
- Next, create another list named “reverseProvList” and utilize the “for” loop that executes from the bottom position or max index.
- The loop breaks when the iteration reaches below the index number “0”.
- Inside the loop, the elements residing at each index in reverse pattern get selected via the “get()” method and then get inserted in a “reverseProvList” list.
- In the end, display the “reverseProvList” list for verification purposes.
The output shows that the original list has been reversed in Java:
Method 6: Reverse a List Using Java 8 Stream API
The “Java 8 Stream API” approach can also be used to reverse a selected list by creating a stream of integers showing list indexes. Then, the “map” method is used to insert the selected list element in the reverse direction. To get a better understanding go through the below code block:
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.*;//importing Required Utilities
public class javabeat {//Creation of Public Class
public static void main(String args[])//initializing the main() method
{
List<String> provList = new ArrayList<>();
provList.add(0, "Champion - 1");
provList.add(1, "Capua - 2");
provList.add(2, "Arena - 3");
System.out.println("\nOriginal List Before Reversal Operation:");
System.out.println("\t" + provList);
List reverseProvList = IntStream
.range(0, provList.size())
.map(i -> provList.size() - 1- i)
.mapToObj(provList::get)
.collect(Collectors.toList());
System.out.println("\nModified List After the Reversal Operation: ");
System.out.println("\t" + reverseProvList);
}
}
The above code works like this:
- First, import the required “Collectors” and “IntStream” stream utilities using the “import” keyword. Then, Create a targeted list “provList” which contains random data inserted using the “add()” method.
- Next, create another list “reverseProvList” with the utilization of an “IntStream” keyword. Assign its size range from “0” to the length of “provList” via the “range()” method.
- Now, apply the “map()” and “mapToObj()” methods to set the position from the bottom of “provList” and retrieve all data from the bottom to the top direction.
- After that, convert the processed retrieved data into a single mutable container which is a list “reverseProvList” in our case.
- Finally, display the content of “reverseProvList” on the console window.
The output generated shows that the reversal operation has been performed on the provided list:
Bonus Tip 1: How to Reverse a LinkedList in Java?
The already discussed methods for “Lists” in the above sections can also be used to reverse data stored in a LinkedList. Only modification is required at the time of the declaration of “LinkedList” and the utilization of the “push()” method instead of “add()” to insert elements in the LinkedList. The code snippet implementing the discussed scenario is shown below:
import java.util.*;//importing Basic Java Utilities
public class javabeat {
public static void main(String args[])//initializing the main() method{
LinkedList<String> provList = new LinkedList<String>();
provList.push("Spartacus - 4");
provList.push("Ganicus - 3");
provList.push("Axios - 2");
provList.push("Lucas - 1");
System.out.println("LinkedList Elements Before the Reversal Operation: \n\t" + provList);
Collections.reverse(provList);
System.out.println("LinkedList Elements After the Reversal Operation: \n\t" + provList);
}
}
The explanation of the above code block:
- First, import the Java default utilities and create a public class “javabeat” that contains the “main()” method.
- In the “main()” method, declare a String type “LinkedList” with the name “provList” and insert random elements in a LinkedList using the “push()” method.
- Pass the “provList” as an argument in the “Collections.reverse()” method to reverse the “provList” LinkedList.
- Finally, display the LinkedList data over the console before and after applying the reversal operation.
The generated output shows that the reversal operation is applied on the LinkedList:
Bonus Tip 2: How to Reverse an ArrayList in Java?
The “ArrayList” or simple “Array” both offer the same functionality of storing data. The size of Array is fixed and you can assign it extra space. However, the “ArrayList” size can be increased or decreased according to user requirements at run time. In order to apply the reversal operation over the ArrayList in Java, use the below code:
import java.util.*;//importing Basic Java Utilities
public class javabeat {//Creation of Public Class
public static void main(String args[])//initializing the main() method
{
ArrayList<String> provList = new ArrayList<String>();
provList.add("Spartacus - 1");
provList.add("Ganicus - 2");
provList.add("Axios - 3");
provList.add("Lucas - 4");
System.out.println("ArrayList Elements Before the Reversal Operation: \n\t" + provList);
Collections.reverse(provList);
System.out.println("\nArrayList Elements After the Reversal Operation: \n\t" + provList);
}
}
The above code works like this:
- Initially, create a “main()” method, and inside it declare an ArrayList named “provList”. This ArrayList contains random elements inserted using the “add()” method.
- After that, display the “provList” elements on the console and pass the “provList” as an argument in the “Collections.reverse()” method. This method will perform the reversal operation.
The output for the above code confirms that ArrayList has been reversed:
That’s all about the procedure to reverse a list in Java.
Conclusion
To reverse a list in Java, pass the targeted ArrayList, LinkedList, or List as an argument to the “Collections.reverse()” method. Other approaches like “Recursion”, “ListIterator”, “Iteration”, or “Java 8 Stream API” are also used and they reduce the lines of code as well. The user can manually create a method by the utilization of the “add()” and “remove()” methods along with the “for” loop. This guide has illustrated all possible approaches to reverse a list in Java.