简体   繁体   中英

Java sorting 2D array

Given an 2d array like this

double[][] y = {{5,1},{0,0},{5,3},{5,2},{10,3},{12,100},{0,0}};

how would I sort it to where its like

{ {0,0},{0,0},{5,1},{5,2},{5,3},{10,3},{12,100} };

this is my current method

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

使用lambda会缩短:D

Arrays.sort(y, (d1, d2) -> Double.compare(d1[0] + d1[1], d2[0] + d2[1]));

this will only work if you are trying to sort based on sub-array sums,

Arrays.sort(sortedPoints, new Comparator<double[]>() {      
            @Override
            public int compare(double[] o1, double[] o2) {
                return Double.compare(o1[0]+o1[1],o2[0]+o2[1]);
            }
        });

made little changes to your code;

You are missing the logic when the first element of the pair is equal in both array.

    Arrays.sort(sortedPoints, new Comparator<double[]>() {      
        @Override
        public int compare(double[] o1, double[] o2) {
            int diff = Double.compare(o1[0], o2[0]);
            if (diff == 0) {
                return Double.compare(o1[1], o2[1]);
            }
            return diff;
        }
    });

You can sort array twice firstly by second field, and then by first.

So, here is an example:

public static void main(String[] args)
{
    System.out.println("Start");
    double[][] y = {{5,1},{0,0},{5,3},{5,2},{10,3},{12,100},{0,0}};

    Arrays.sort(y, (var a, var b) -> (int)(a[1]- b[1]));
    Arrays.sort(y, (var a, var b) -> (int)(a[0]- b[0]));

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

    System.out.println("End");}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM