Search code examples
javaarrayssortingcomparator

How to use Java Comparator to sort an array of arrays?


The problem is to sort an array of two element arrays based on the absolute difference of the elements of those inner arrays in descending order, so {{1, 3}, {4, 12}, {5, 8} would be sorted as {{4, 12}, {5, 8}, {1, 3}}

I have code like this:

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

public class Main {

    public static void main(String[] args) {
        Integer[][] arr = {{1, 3}, {3, 12}, {12, 16}};

        Arrays.sort(arr, Comparator.comparing(arr, (Integer[] a, Integer[] b) -> a[1] + b[1] - a[0] - b[0]);
    }
}

but I get this error. It says "cannot infer functional interface type".

Edit: upon changing the above to

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

public class Main {

    public static void main(String[] args) {
        Integer[][] arr = {{1, 3}, {3, 12}, {12, 16}};

        Arrays.sort(arr, Comparator.comparing(a -> a[0] - a[1]));

        for (int i = 0; i < arr.length; i++ ) {
            System.out.print("{" + arr[i][0] + ", " + arr[i][1] + "}, ");
        }
    }
}

I get the desired output, but I was unable to get the reversed() method to work like in this answer. I get this error where it says "Array type expected; found: 'java.lang.Object'"

I suppose my question is mostly answered but if someone could clarify the issue with reversed I'd appreciate it.

Edit: and sorry, I neglected to use Math.abs() as in the context of my problem I know the array is always increasing like {2,3}, {3,6}, {6,8}... etc


Solution

  • Descending:

    Arrays.sort(arr, (o1, o2) -> Math.abs(o2[0] - o2[1]) - Math.abs(o1[0] - o1[1]));
    

    Ascending:

    Arrays.sort(arr, Comparator.comparingInt(o -> Math.abs(o[0] - o[1])));