The previous tutorial was all about sorting an array in ascending order. In this post we are going to learn how to sort an array in Descending (Reverse) Order.
Example
Here we have two arrays, one is integer array and another one is String array. We are sorting both the arrays in reverse order.
import java.util.Arrays; import java.util.Collections; class SortArrayExample { public static void main(String[] args) { // int Array Integer[] intArray = new Integer[] { new Integer(15), new Integer(9), new Integer(16), new Integer(2), new Integer(30) }; // Sorting int Array in descending order Arrays.sort(intArray, Collections.reverseOrder()); // Displaying elements of int Array System.out.println("Int Array Elements in reverse order:"); for (int i = 0; i < intArray.length; i++) System.out.println(intArray[i]); // String Array String[] stringArray = new String[] { "FF", "PP", "AA", "OO", "DD" }; // Sorting String Array in descending order Arrays.sort(stringArray, Collections.reverseOrder()); // Displaying elements of String Array System.out.println("String Array Elements in reverse order:"); for (int i = 0; i < stringArray.length; i++) System.out.println(stringArray[i]); } }
Output:
Int Array Elements in reverse order: 30 16 15 9 2 String Array Elements in reverse order: PP OO FF DD AA
niks says
Reverse order can be done by sorting it first using Arrays.sort() and then just reverse them.