Home > Java > javaTutorial > How to Sort an Array in Descending Order in Java?

How to Sort an Array in Descending Order in Java?

DDD
Release: 2024-11-02 15:19:02
Original
290 people have browsed it

How to Sort an Array in Descending Order in Java?

Sorting an Array in Descending Order in Java

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template