Reverse an ArrayList
To reverse an ArrayList in Java, you can use java.util.Collections class, or use any looping technique to traverse the elements and create another list with elements added in reverse order.
Reverse ArrayList using java.util.Collections
Collection.reverse() method takes the ArrayList as argument and reverses the order of elements present in the list. Following is the syntax of reverse() method.
Collections.reverse(myList);
In the following program, we have created an ArrayList with some elements, and reversed the ArrayList using Collections class.
Java Program
import java.util.ArrayList;
import java.util.Collections;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> myList = new ArrayList<String>();
myList.add("Google");
myList.add("Apple");
myList.add("Samsung");
myList.add("Asus");
Collections.reverse(myList);
for(String element: myList) {
System.out.println(element);
}
}
}
Output
Asus
Samsung
Apple
Google
Reverse ArrayList using For Loop
You can also reverse an ArrayList using Java For Loop. Iterate from starting to middle of the ArrayList, and swap the element with the element on the other side of the ArrayList.
In the following program, we have created an ArrayList with some elements, and reversed the ArrayList using for loop statement.
Java Program
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> myList = new ArrayList<String>();
myList.add("Google");
myList.add("Apple");
myList.add("Samsung");
myList.add("Asus");
for(int index=0; index < myList.size()/2; index++) {
String temp = myList.get(index);
myList.set(index, myList.get(myList.size() - index - 1));
myList.set(myList.size()-index-1, temp);
}
for(String element: myList) {
System.out.println(element);
}
}
}
Output
Asus
Samsung
Apple
Google
Conclusion
In this Java Tutorial, we learned how to reverse an ArrayList in Java using Collections and Looping statements.