- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get reverse order using Comparator in Java
The objects of a user defined class can be ordered using the Comparator interface in Java. The java.util.Collections.reverseOrder() method reverses the order of an element collection using a Comparator.
A program that demonstrates this is given as follows −
Example
import java.util.Arrays; import java.util.Collections; import java.util.Comparator; public class Demo { public static void main(String args[]) throws Exception { Comparator comparator = Collections.reverseOrder(); { "John", "Amy", "Susan", "Peter" }; int n = str.length; System.out.println("The array elements are: "); for (int i = 0; i < n; i++) { System.out.println(str[i]); } Arrays.sort(str, comparator); System.out.println("
The array elements sorted in reverse order are: "); for (int i = 0; i < n; i++) { System.out.println(str[i]); } } }
The output of the above program is as follows −
The array elements are: John Amy Susan Peter The array elements sorted in reverse order are: Susan Peter John Amy
Now let us understand the above program.
The Comparator is created along with reverseOrder() method. Then the string array str[] is defined and then the elements are displayed using a for loop. A code snippet which demonstrates this is as follows −
Comparator comparator = Collections.reverseOrder(); { "John", "Amy", "Susan", "Peter" }; int n = str.length; System.out.println("The array elements are: "); for (int i = 0; i < n; i++) { System.out.println(str[i]); }
The string array is sorted in reverse order using the java.util.Arrays.sort() method. Then the array elements are displayed using a for loop. A code snippet which demonstrates this is as follows −
Arrays.sort(str, comparator); System.out.println("
The array elements sorted in reverse order are: "); for (int i = 0; i < n; i++) { System.out.println(str[i]); }