Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort int array in descending order using java 8 features (stream, lambda, etc)

Tags:

java

java-8

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.

like image 895
JBT Avatar asked Aug 03 '15 01:08

JBT


2 Answers

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.

like image 79
Pshemo Avatar answered Oct 12 '22 13:10

Pshemo


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.

like image 37
Alexis C. Avatar answered Oct 12 '22 12:10

Alexis C.