Reverse a List in Java (In-place)
This post will discuss how to reverse a list in Java by modifying the list in-place. That means that the conversion should occur without using any auxiliary list by overwriting the existing elements of the specified list.
Assume that the specified list is modifiable. For immutable lists, an UnsupportedOperationException should be thrown.
1. Using Collections.reverse() method
The idea is to use the Collections.reverse() method to reverse the order of the elements in the specified list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; // Program to in-place reverse a list in Java class Main { public static void main(String[] args) { List<String> colors = new ArrayList<>(Arrays.asList("RED", "BLUE", "BLACK")); Collections.reverse(colors); System.out.println(colors); } } |
Output:
[BLACK, BLUE, RED]
2. Using List.add() with List.remove() method
Another approach to in-place reverse a list is to reorder the elements present in the list using a for-loop, which removes an element from the end of the list and insert it into the very beginning, one at a time.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import java.util.ArrayList; import java.util.Arrays; import java.util.List; // Program to in-place reverse a list in Java class Main { public static void main(String[] args) { List<String> colors = new ArrayList<>(Arrays.asList("RED", "BLUE", "BLACK")); for (int i = 0, j = colors.size() - 1; i < j; i++) { colors.add(i, colors.remove(j)); } System.out.println(colors); } } |
Output:
[BLACK, BLUE, RED]
3. Using Recursion
We can also use recursion to reverse a list in-place, as demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
import java.util.ArrayList; import java.util.Arrays; import java.util.List; // Program to in-place reverse a list in Java class Main { public static<T> void reverseList(List<T> list) { // base case: the list is empty, or only one element is left if (list == null || list.size() <= 1) { return; } // remove the first element T value = list.remove(0); // recur for remaining items reverseList(list); // insert the top element back after recurse for remaining items list.add(value); } public static void main(String[] args) { List<String> colors = new ArrayList<>(Arrays.asList("RED", "BLUE", "BLACK")); reverseList(colors); System.out.println(colors); } } |
Output:
[BLACK, BLUE, RED]
That’s all about reversing a List in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)