3

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.

0

5 Answers 5

4

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]
Sign up to request clarification or add additional context in comments.

1 Comment

really useful answer, as it shows two alternatives for the desired result.
2

Assuming it's the Comparator<Integer> that you want to specify using a lambda :

Arrays.sort(arr, (x,y) -> y-x);

Comparator<Integer> is a @FunctionalInterface and can be implemented by using a lambda to define its abstract method int compare(T in1, T in2). This lambda will have to be of the form (param1, param2) -> expression that returns an int to conform to the signature of compare.

The method must "Return a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.". In our case since we sort in descending order we want the smallest integer to be considered as "greatest" in the context of our sort order, which we achieve by substracting the first element from the second (if in1 > in2 then in2 - in1 < 0 then in1 comes before in2 and conversely).

You can try it here.

Comments

1

If you look at the JDK Documentation : Arrays.sort : This method accept two arguments :

  1. the array to be sorted
  2. the Comparator used for sorting

for the comparator you have 3 choices :

  1. use a separate classes
package com.nejeoui;

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

public class Example {
    
    public static void main(String[] args) {
        Integer[] arr = {13, 7, 6, 45, 21, 9, 2, 100};
        Arrays.sort(arr, new MyComparator());
    }

}

class MyComparator implements Comparator<Integer>{

    @Override
    public int compare(Integer o1, Integer o2) {
        
        return o1-o2;
    }
    
}
  1. use an anonymous class
package com.nejeoui;

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

public class Example {
    
    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 o1, Integer o2) {
                
                return o1-o2;
            }
        });
    }

}
  1. use a lambda expression (Java 1.8)
package com.nejeoui;

import java.util.Arrays;

public class Example {
    public static void main(String[] args) {
        Integer[] arr = {13, 7, 6, 45, 21, 9, 2, 100};
        Arrays.sort(arr,  (o1,o2)-> o1-o2 );
    }

}

As you may notice the Lambda expression is less verbose and elegant way to write anonymous classes from a functional interface

Comments

0

You can use Arrays.stream() like this:

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

    Integer[] sortedArr = Arrays.stream(arr)    // stream the content
                            // sort it in reverse order
                            .sorted(Collections.reverseOrder())
                            // and define a data structure for the result
                            .toArray(Integer[]::new);
    // output the result
    Arrays.stream(sortedArr).forEach(i -> System.out.print(i + " "));
}

The output is

100 45 21 13 9 7 6 2 

Comments

0

You can use Arrays.asList to make it List<Integer> and then use stream.sorted() method to sort integer list like this:

Arrays.asList(arr).stream().sorted().forEach(System.out::println);

And for reverse :

Arrays.asList(arr).stream().sorted(Comparator.reverseOrder()).forEach(System.out::println);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.