Appearance
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:
java
import java.util.Arrays;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
Integer[] 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 object type that implements the Comparable interface. Note that Arrays.sort with a Comparator does not work with primitive arrays (like int[] or double[]). For example, to sort an array of strings in descending order:
java
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:
java
import java.util.Arrays;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
Integer[] arr = {3, 1, 2, 5, 4};
Arrays.sort(arr, Collections.reverseOrder());
System.out.println(Arrays.toString(arr)); // [5, 4, 3, 2, 1]
}
}If you need to sort a primitive array (e.g., int[]) in descending order, you can convert it to a stream, sort it, and convert it back:
java
import java.util.Arrays;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
int[] arr = {3, 1, 2, 5, 4};
arr = Arrays.stream(arr)
.boxed()
.sorted(Comparator.reverseOrder())
.mapToInt(Integer::intValue)
.toArray();
System.out.println(Arrays.toString(arr)); // [5, 4, 3, 2, 1]
}
}Either way, this will sort the array in descending order.