Java Array Sort descending? Java Array Sort descending? arrays arrays

Java Array Sort descending?


You could use this to sort all kind of Objects

sort(T[] a, Comparator<? super T> c) Arrays.sort(a, Collections.reverseOrder());

Arrays.sort() cannot be used directly to sort primitive arrays in descending order. If you try to call the Arrays.sort() method by passing reverse Comparator defined by Collections.reverseOrder() , it will throw the error

no suitable method found for sort(int[],comparator)

That will work fine with 'Array of Objects' such as Integer array but will not work with a primitive array such as int array.

The only way to sort a primitive array in descending order is, first sort the array in ascending order and then reverse the array in place. This is also true for two-dimensional primitive arrays.


for a list

Collections.sort(list, Collections.reverseOrder());

for an array

Arrays.sort(array, Collections.reverseOrder());


You can use this:

    Arrays.sort(data, Collections.reverseOrder());

Collections.reverseOrder() returns a Comparator using the inverse natural order. You can get an inverted version of your own comparator using Collections.reverseOrder(myComparator).