Java sort 2d array by column

www‮iruttual.‬.com
Java sort 2d array by column
/**
 * @author lautturi.com 
 * Java example: java arrays sort 2d array
 */

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]));
		}
		
		// use lambda function to compare two elements
		Arrays.sort(arr, (a, b) -> Integer.compare(a[0], b[0])); //in increasing order
//		Arrays.sort(arr, (a, b) -> Integer.compare(b[0], a[0])); //in decreasing/reverse order
//		or
//		Arrays.sort(myArr, (a, b) -> a[0] - b[0]);
//		Arrays.sort(myArr, (a, b) -> a[1] - b[2]); // order 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]
Created Time:2017-10-09 13:05:22  Author:lautturi