Skip to content
Advertisement

Sort Int array using lambda java 8

Just to understand Lambda better I have a array of integer like below –

JavaScript

I want to sort the array using Lambda function of Java 8. I have used

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

but I want to sort it using Lambda of Java 8 any detailed explanation would be appreciated.

Advertisement

Answer

Arrays#sort requires a Comparator to sort the array. You can reverse the order of arguments to Comparator#compare for the comparison to happen in the reverse order.

Without lambda, you would do it as

JavaScript

Output:

JavaScript

Lambda helps you get rid of all the things enclosed by a rectangle in the picture given below:

enter image description here

The things enclosed by a green rectangle are not required when you have just one statement in the body.

Thus, using lambda, the code becomes:

JavaScript

Output:

JavaScript
Advertisement