- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to Reverse an ArrayList in Java
Reversing an ArrayList means changing the order of its elements so that the first element becomes the last, the second becomes the second-last, and so on. Java provides a simple method to reverse the order of elements in an ArrayList using Collections.reverse(). The following are the ways to reverse an ArrayList
Using Collections.reverse() method
Manually reversing an ArrayList
Reverse an ArrayList Using Collections.reverse() Method
The reverseOrder() method of Java Collections obtains a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.
Syntax
Following is the declaration for java.util.Collections.reverseOrder() method.
public staticComparator reverseOrder()
Example
The following example reverses an array list by using Collections.reverse(ArrayList)method
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
arrayList.add("A");
arrayList.add("B");
arrayList.add("C");
arrayList.add("D");
arrayList.add("E");
System.out.println("Before Reverse Order: " + arrayList);
Collections.reverse(arrayList);
System.out.println("After Reverse Order: " + arrayList);
}
}
Output
Before Reverse Order: [A, B, C, D, E] After Reverse Order: [E, D, C, B, A]
Reverse an ArrayList Manually
The process involves swapping elements from both ends of the array until they meet in the middle.
Example
The following is another example of reversing an array
public class HelloWorld {
public static void main(String[] args) {
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
System.out.println("Array before reverse:");
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
for (int i = 0; i < numbers.length / 2; i++) {
int temp = numbers[i];
numbers[i] = numbers[numbers.length - 1 - i];
numbers[numbers.length - 1 - i] = temp;
}
System.out.println("\nArray after reverse:");
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
}
}
Output
Array before reverse: 1 2 3 4 5 6 7 8 9 10 Array after reverse: 10 9 8 7 6 5 4 3 2 1