Home > Java > javaTutorial > How to Sort Java Arrays in Descending Order?

How to Sort Java Arrays in Descending Order?

Mary-Kate Olsen
Release: 2024-11-01 23:56:29
Original
915 people have browsed it

How to Sort Java Arrays in Descending Order?

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

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:

  1. Sort in Ascending Order: First, sort the array in ascending order using Arrays.sort().
  2. Reverse the Array: After sorting in ascending order, reverse the array to obtain descending order. You can use Collections.reverse() or the reverse() method provided by Java for newer versions.

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

Alternative Methods:

  • Using the Arrays.sort() method with a custom comparator that implements the Comparator interface and reverses the ordering.
  • Using streams and the sorted() method with a custom comparator, similar to the object sorting approach.

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template