How to sort a two-dimensional array in Java?

To sort a two-dimensional array, you can use the sort() method in the Arrays class. Here is an example code showing how to sort a two-dimensional array.

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[][] arr = {{4, 2}, {1, 7}, {3, 5}};
        
        // 排序前
        System.out.println("排序前:");
        for (int[] row : arr) {
            System.out.println(Arrays.toString(row));
        }
        
        // 对二维数组按第一列进行排序
        Arrays.sort(arr, (a, b) -> Integer.compare(a[0], b[0]));
        
        // 排序后
        System.out.println("排序后:");
        for (int[] row : arr) {
            System.out.println(Arrays.toString(row));
        }
    }
}

In the code above, we defined a 2D array arr and sorted it using the Arrays.sort() method. During the sorting process, we provided a comparator that specified sorting by the first column. The logic of the comparator can be modified as needed for different types of sorting.

bannerAds