In Java, the Arrays class provides a sort method for ascending order sorting of an array. However, if the need arises to order an array in descending order, the "EASY" way is to use the sort method in conjunction with the Collections.reverseOrder() comparator.
The following code illustrates this approach:
<code class="java">Integer[] numbers = {5, 2, 8, 3, 1}; Arrays.sort(numbers, Collections.reverseOrder()); System.out.println(Arrays.toString(numbers)); // Output: [8, 5, 3, 2, 1]</code>
Here, Collections.reverseOrder() provides a comparator that reverses the natural ordering of elements, effectively sorting the array in descending order. This method is ideal for sorting arrays of objects.
For primitive arrays (e.g., int arrays), the Arrays.sort() method alone cannot be used directly for descending order sorting. Attempting to use sort with Collections.reverseOrder() on a primitive array will result in an error.
The solution for primitive arrays is to first sort the array in ascending order using the sort method, and then reverse the array in place using the reverse method.
Here is an example:
<code class="java">int[] numbers = {5, 2, 8, 3, 1}; Arrays.sort(numbers); ArrayUtils.reverse(numbers); System.out.println(Arrays.toString(numbers)); // Output: [8, 5, 3, 2, 1]</code>
This approach is applicable to both one-dimensional and two-dimensional primitive arrays.
The above is the detailed content of How to Sort an Array in Descending Order in Java?. For more information, please follow other related articles on the PHP Chinese website!