Arrays.sort()对二维数组排序

对二维数组{x,y}的y进行从小到大排序
方法1:
重写比较器写法

public class Test {

   public static void main(String[] args) {
       int[][] nums = {{3, 1}, {4, 2}};
       Arrays.sort(nums,new Comparator<int[]>(){
            @Override
            public int compare(int[] a,int[] b){
                if(a[1]==b[1]){
                    return a[0]-b[0];
                }else{
                    return a[1]-b[1];
                }
            }
        });
 		for (int i = 0; i < nums.length; i++) {
            for (int j = 0; j < nums[0].length; j++) {
                System.out.print(nums[i][j]+" ");
            }
            System.out.println();
        }
    }

}
        

方法2:
Lambda表达式写法

public class Test {

   public static void main(String[] args) {
        int[][] nums = {{3, 1}, {4, 2}};
        Arrays.sort(nums, (event1, event2) -> {
            return event1[1] == event2[1] ? event1[0] - event2[0] : event1[1] - event2[1];
        });
        for (int i = 0; i < nums.length; i++) {
            for (int j = 0; j < nums[0].length; j++) {
                System.out.print(nums[i][j]+" ");
            }
            System.out.println();
        }

    }

}

方法3:
更简洁的Lambda表达式

public class Test {

    public static void main(String[] args) {
        int[][] nums = {{3, 1}, {4, 0}};
        Arrays.sort(nums, (o1, o2) -> o1[1] - o2[1]);
        for (int i = 0; i < nums.length; i++) {
            for (int j = 0; j < nums[0].length; j++) {
                System.out.print(nums[i][j]+" ");
            }
            System.out.println();
        }
    }

}

输出:
3 1
4 2

你可能感兴趣的:(Java)