Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the second argument doing in this function?

Arrays.sort(courses, (a, b) -> a[1] - b[1]);
PriorityQueue<Integer> queue = new PriorityQueue<>((a, b) -> b - a);

I tried looking at the docs but cannot understand what the second argument is responsible for. I know that .sort(array, 1, 4) means sort from index 1 to 3. But in this case, the arrow with -> a[1] - b[1] and ((a, b) -> b - a) is what I am unable to understand.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The arrow represents a lambda function that compares any two arguments a and b. Before lambdas were introduced (in Java 8), the sort would look like this:

Arrays.sort(courses, new Comparator<int[]>() {
    @Override
    public int compare(int[] a, int[] b) {
        return a[1] - b[1];
    }
});

I’m taking a guess at the type of a but feel free to substitute int[] with any numeric array.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading