Collections.reverse() Method in Java with Examples
reverse() method of Collections class as the name itself suggests is used for reversing elements been there up in the object in which they are stored. It reverses the order of elements in a list passed as an argument.
This class is present in java.util package so do syntax is as follows:
import java.util.Collections;
Collections.reverse(class_obj);
Illustration:
Input : {1, 2, 3, 4}
Output : {4, 3, 2, 1}
Parameter: Object of a class whose elements are to be reversed.
public static void reverse(List myList)
Exception Thrown: It throws UnsupportedOperationException if the specified list or its list-iterator does not support the set operation.
Let us see the usage of this method via use cases listed below as follows:
- Reversing an ArrayList
- Reversing a LinkedList
- Reversing an array
Let us implement this method of Collections class by implementing the same in clan java codes as provided below as follows:
Case 1: Reversing an ArrayList
JAVA
import java.util.*;
public class GFG {
public static void main(String[] args)
{
List<String> mylist = new ArrayList<String>();
mylist.add( "practice" );
mylist.add( "code" );
mylist.add( "quiz" );
mylist.add( "geeksforgeeks" );
System.out.println( "Original List : " + mylist);
Collections.reverse(mylist);
System.out.println( "Modified List: " + mylist);
}
}
|
Output
Original List : [practice, code, quiz, geeksforgeeks]
Modified List: [geeksforgeeks, quiz, code, practice]
Case 2: Reversing a LinkedList
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
List<String> mylist = new LinkedList<String>();
mylist.add( "practice" );
mylist.add( "code" );
mylist.add( "quiz" );
mylist.add( "geeksforgeeks" );
System.out.println( "Original List : " + mylist);
Collections.reverse(mylist);
System.out.println( "Modified List: " + mylist);
}
}
|
Output
Original List : [practice, code, quiz, geeksforgeeks]
Modified List: [geeksforgeeks, quiz, code, practice]
If we peek through the above programs then there is only a minute signature detail that we are just creating an object of LinkedList class instead of Array class as seen in example1A. For LinkedList, we just did change as shown below in the above codes:
LinkedList in "List mylist = new ArrayList();".
Case 3: Reversing an array: Arrays class in Java doesn’t have a reverse method. We can use Collections.reverse() to reverse an array also as shown below as follows:
Example
Java
import java.util.*;
public class GFG {
public static void main(String[] args)
{
Integer arr[] = { 10 , 20 , 30 , 40 , 50 };
System.out.println( "Original Array : "
+ Arrays.toString(arr));
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]
Last Updated :
10 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...