Skip to content
Advertisement

Sort arrays using lambda

I want revers-sort java8. I don’t want use stream.

Here is an example:

int[] a = {1, 2, 3, 4, 5};

I want it like this: {5, 4, 3, 2, 1};

So my code is this

Arrays.sort(a, (o1, o2) -> o2 - o1);

Arrays.sort(arr, (a,b) ->Integer.compare(b ,a));

But I get an error message:

Operator ‘-‘ cannot be applied to ‘T’, ‘T’

How can I reverse sort and sort?

Is there a better way?

Advertisement

Answer

You can try

int[] sortedArray = Arrays.stream(a)
        .boxed()
        .sorted(Comparator.reverseOrder())
        .mapToInt(Integer::intValue)
        .toArray();

if you use Integer data type then even easier

Arrays.sort(a, Comparator.reverseOrder());

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement