Search code examples
javaarraysmultidimensional-arraycomparator

Java Comparator class to sort arrays


Say, we have the following 2-dimensional array:

int camels[][] = new int[n][2];

How should Java Comparator class be declared to sort the arrays by their first elements in decreasing order using Arrays.sort(camels, comparator)? The compare function for reference is:

@Override public int compare(int[] a, int [] b)
{
    return b[0] - a[0];
}

Solution

  • [...] How should Java Comparator class be declared to sort the arrays by their first elements in decreasing order [...]

    Here's a complete example using Java 8:

    import java.util.*;
    
    public class Test {
    
        public static void main(String args[]) {
    
            int[][] twoDim = { {1, 2}, {3, 7}, {8, 9}, {4, 2}, {5, 3} };
    
            Arrays.sort(twoDim, Comparator.comparingInt(a -> a[0])
                                          .reversed());
    
            System.out.println(Arrays.deepToString(twoDim));
        }
    }
    

    Output:

    [[8, 9], [5, 3], [4, 2], [3, 7], [1, 2]]
    

    For Java 7 you can do:

    Arrays.sort(twoDim, new Comparator<int[]>() {
        @Override
        public int compare(int[] o1, int[] o2) {
            return Integer.compare(o2[0], o1[0]);
        }
    });
    

    If you unfortunate enough to work on Java 6 or older, you'd do:

    Arrays.sort(twoDim, new Comparator<int[]>() {
        @Override
        public int compare(int[] o1, int[] o2) {
            return ((Integer) o2[0]).compareTo(o1[0]);
        }
    });