Skip to content
Advertisement

Sort Int array using lambda java 8

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

Integer[] arr = {13, 7, 6, 45, 21, 9, 2, 100};

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

import java.util.Arrays;
import java.util.Comparator;

public class Main {
    public static void main(String[] args) {
        Integer[] arr = { 13, 7, 6, 45, 21, 9, 2, 100 };

        Arrays.sort(arr, new Comparator<Integer>() {
            @Override
            public int compare(Integer x, Integer y) {
                return Integer.compare(y, x);
            }
        });
        System.out.println(Arrays.toString(arr));
    }
}

Output:

[100, 45, 21, 13, 9, 7, 6, 2]

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:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        Integer[] arr = { 13, 7, 6, 45, 21, 9, 2, 100 };
        Arrays.sort(arr, (x, y) -> Integer.compare(y, x));
        System.out.println(Arrays.toString(arr));
    }
}

Output:

[100, 45, 21, 13, 9, 7, 6, 2]
Advertisement