java.util.Collections.reverse() method is a java.util.Collections class method. It reverses the order of elements in a list passed as an argument.
// Reverses elements of myList and returns Nothing. // For example, if list contains {1, 2, 3, 4}, it converts // list to {4, 3, 2, 1} public static void reverse(List myList) It throws UnsupportedOperationException if the specified list or its list-iterator does not support the set operation.
Reversing an ArrayList or LinkedList.
// Java program to demonstrate working of java.utils. // Collections.reverse() import java.util.*; public class ReverseDemo { public static void main(String[] args) { // Let us create a list of strings List<String> mylist = new ArrayList<String>(); mylist.add( "practice" ); mylist.add( "code" ); mylist.add( "quiz" ); mylist.add( "geeksforgeeks" ); System.out.println( "Original List : " + mylist); // Here we are using reverse() method // to reverse the element order of mylist Collections.reverse(mylist); System.out.println( "Modified List: " + mylist); } } |
Output:
Original List : [practice, code, quiz, geeksforgeeks] Modified List: [geeksforgeeks, quiz, code, practice]
For Linkedlist, we just need to replace ArrayList with LinkedList in “List
Arrays class in Java doesn’t have reverse method. We can use Collections.reverse() to reverse an array also.
// Java program to demonstrate reversing of array // with Collections.reverse() import java.util.*; public class ReverseDemo { public static void main(String[] args) { // Let us create an array of integers Integer arr[] = { 10 , 20 , 30 , 40 , 50 }; System.out.println( "Original Array : " + Arrays.toString(arr)); // Please refer below post for details of asList() Collections.reverse(Arrays.asList(arr)); System.out.println( "Modified Array : " + Arrays.toString(arr)); } } |
Output:
Original Array : [10, 20, 30, 40, 50] Modified Array : [50, 40, 30, 20, 10]
This article is contributed by Mohit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.