Search code examples
javajava-8

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


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.


Solution

  • 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.