Learn to Use the Collections.reverse() Method
The Collections.reverse() method is a simple way to reverse the order of elements in a list or an array in Java. In this article, we will explore how to use this method step-by-step with examples.
Reversing an ArrayList or LinkedList
To reverse the order of elements in an ArrayList or LinkedList, follow these steps:
- Create a list of elements using the ArrayList or LinkedList class.
sqlList<Integer> list = new ArrayList<Integer>();
or
sqlList<Integer> list = new LinkedList<Integer>();
- Add elements to the list.
csharplist.add(10);
list.add(20);
list.add(30);
- Print the original order of the list.
goSystem.out.println(list); // [10, 20, 30]
- Use the Collections.reverse() method to reverse the order of elements.
luaCollections.reverse(list);
- Print the reversed order of the list.
goSystem.out.println(list); // [30, 20, 10]
Reversing an Array
The Arrays class in Java does not have a built-in reverse() method. However, we can use the Collections.reverse() method to reverse an array by converting it to a list using the Arrays.asList() method.
- Create an array of elements.
cssInteger[] arr = {10, 20, 30};
- Convert the array to a list.
phpList<Integer> list = Arrays.asList(arr);
- Print the original order of the array.
goSystem.out.println(Arrays.toString(arr)); // [10, 20, 30]
- Use the Collections.reverse() method to reverse the order of elements in the list.
luaCollections.reverse(list);
- Print the reversed order of the array.
goSystem.out.println(Arrays.toString(arr)); // [30, 20, 10]
Example Code
Here is the complete code for both examples.
csharpimport java.util.*;
public class ReverseExample {
public static void main(String[] args) {
// Reversing an ArrayList or LinkedList
List<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add(20);
list.add(30);
System.out.println(list); // [10, 20, 30]
Collections.reverse(list);
System.out.println(list); // [30, 20, 10]
// Reversing an Array
Integer[] arr = {10, 20, 30};
List<Integer> arrList = Arrays.asList(arr);
System.out.println(Arrays.toString(arr)); // [10, 20, 30]
Collections.reverse(arrList);
System.out.println(Arrays.toString(arr)); // [30, 20, 10]
}
}
In conclusion, the Collections.reverse() method is a convenient way to reverse the order of elements in a list or an array in Java. By following the steps outlined in this article, you can easily implement this method in your own code.