Sort Java Arrays in Descending Order
Sorting arrays in descending order is not directly supported by the Arrays class. However, there are methods available to achieve this.
Sorting Objects in Descending Order
If your array contains objects, you can use the sort() method with a comparator that reverses the sorting order:
<code class="java">Arrays.sort(a, Collections.reverseOrder());</code>
This will sort the array in descending order based on the natural ordering of the objects.
Sorting Primitive Arrays in Descending Order
For primitive arrays, you need to follow a two-step process:
Example for int Array:
<code class="java">int[] arr = {5, 2, 8, 1, 3}; // Sort in ascending order Arrays.sort(arr); // Reverse the array Collections.reverse(Arrays.asList(arr)); // Array is now sorted in descending order</code>
Alternative Methods:
The above is the detailed content of How to Sort Java Arrays in Descending Order?. For more information, please follow other related articles on the PHP Chinese website!