Surprisingly, it seems there was no simple, one-liner kind of solution in java to sort int array in descending order before java 8. For example, check this post. Now that we have java 8, is there an elegant, simple, one-liner way using java 8 features, such as stream and lambda expression, to sort an int array in descending order?
Edit
I am interested in a solution for int[]
, not Integer[]
.
Edit
I am interested in a solution that only uses JAVA SE library.
With guava you could simply write
Ints.asList(a).sort(Comparator.reverseOrder());
It may be not so efficient since it requires boxing int to Integer, but it is elegant one-liner.
You can also write something like
int[] sorted = IntStream.of(a)
.boxed()
.sorted(Comparator.reverseOrder())
.mapToInt(i -> i)
.toArray();
but this also suffers from boxing and it needs to create new array.
Anyway I doubt you will find nice solution in standard Java free of boxing since Comparator<T>
can accept only objects. For now best way would be using Arrays.sort
and reverse its order manually.
int[] arr = ...;
Arrays.sort(arr);
int[] reversed = IntStream.range(0, arr.length)
.map(i -> arr[arr.length-i-1])
.toArray();
is probably the closest you could do if you don't want to box the int
into its respective wrapper class for each value in the array.
If you suffer from performances by doing the sort once (O(nlogn)
) and the reverse operation after (O(n)
), you might want to look into Arrays.parallelSort
and parallelize the IntStream
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With