/** * @author lautturi.com * Java example: sort 2d-array by column in java */ import java.util.*; public class Lautturi { public static void main(String[] args) { int[][] arr = {{3, 2},{1,4},{6,7},{5,9},{8,12}}; for(int i=0;i<arr.length;i++){ System.out.println(Arrays.toString(arr[i])); } Arrays.sort(arr, new Comparator<int[]>() { public int compare(int[] a, int[] b) { return Integer.compare(a[0], b[0]); // sorted by first column // return Integer.compare(b[0], a[0]); // sorted by first column in decreasing/reverse order // return Integer.compare(a[1], b[1]); // sorted by second column } }); System.out.println("---Sorted 2D-Array-----"); for(int i=0;i<arr.length;i++){ System.out.println(Arrays.toString(arr[i])); } } }
output:
[3, 2] [1, 4] [6, 7] [5, 9] [8, 12] ---Sorted 2D-Array----- [1, 4] [3, 2] [5, 9] [6, 7] [8, 12]