This post will discuss how to sort an array of primitives in descending order in Java.

It’s not possible to sort an array of primitives in “descending” order using the Arrays.sort() and Collections.sort() method, since the comparator work on the Wrapper classes and objects instead of the primitives. For instance, the following code reverse sort an Integer array using the Arrays.sort() method.

Download  Run Code

Output:

[5, 4, 3, 2, 1]

 
However, there are several indirect ways to sort an array of primitives in reverse order:

1. Java 8 Stream API

The idea is to use Java 8 Streams to box the primitive int to Integer and then sort it backwards using the Collections.reverseOrder() comparator. Then, collect the sorted sequence back into a primitive array. This is demonstrated below:

Download  Run Code

Output:

[5, 4, 3, 2, 1]

2. Using Guava

Guava’s asList(int...) method returns a fixed-size list backed by the specified array, similar to Arrays.asList(Object[]). We can use it to get a list view of the array and then sort it using the Collections.sort() method.

The following code demonstrates this by applying the Collections.reverseOrder() comparator to the underlying primitive array.

Download Code

Output:

[5, 4, 3, 2, 1]

 
Here’s an example using List.sort() method.

Download Code

Output:

[5, 4, 3, 2, 1]

3. Sort and Reverse

Another plausible, simple, but less efficient solution, is to sort the array in ascending order and reverse it. The following code demonstrates this Stream API.

Download  Run Code

Output:

[5, 4, 3, 2, 1]

That’s all about sorting an array in descending order in Java.