Search code examples
javaarrayssortingmatrix

java Arrays.sort 2d array


I am looking to sort the following array based on the values of [][0]

double[][] myArr = new double[mySize][2];

so for example, myArr contents is:

1      5
13     1.55
12     100.6
12.1   .85

I want it to get to:

1      5
12     100.6
12.1   .85
13     1.55

I am looking to do this without having to implement my own sort.


Solution

  • Use Overloaded Arrays#Sort(T[] a, Comparator c) which takes Comparator as the second argument.

    double[][] array= {
    {1, 5},
    {13, 1.55},
    {12, 100.6},
    {12.1, .85} };
    
    java.util.Arrays.sort(array, new java.util.Comparator<double[]>() {
        public int compare(double[] a, double[] b) {
            return Double.compare(a[0], b[0]);
        }
    });
    

    JAVA-8: Instead of that big comparator, we can use lambda function as following-

    Arrays.sort(array, Comparator.comparingDouble(o -> o[0]));