Java Array Sort descending?
To sort an array in descending order in Java, you can use the Arrays.sort
method and pass it a comparator that compares the elements in reverse order. Here's an example of how to sort an array of integers in descending order:
import java.util.Arrays;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
int[] arr = {3, 1, 2, 5, 4};
Arrays.sort(arr, Comparator.reverseOrder());
System.out.println(Arrays.toString(arr)); // [5, 4, 3, 2, 1]
}
}
You can use this same approach to sort an array of any type that implements the Comparable
interface. For example, to sort an array of strings in descending order:
import java.util.Arrays;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
String[] arr = {"apple", "banana", "cherry"};
Arrays.sort(arr, Comparator.reverseOrder());
System.out.println(Arrays.toString(arr)); // [cherry, banana, apple]
}
}
Alternatively, you can use the Collections.reverseOrder
method to create a comparator that compares elements in reverse order, and pass it to the Arrays.sort
method:
import java.util.Arrays;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
int[] arr = {3, 1, 2, 5, 4};
Arrays.sort(arr, Collections.reverseOrder());
System.out.println(Arrays.toString(arr)); // [5, 4, 3, 2, 1]
}
}
Either way, this will sort the array in descending order.