The Arrays class and the Comparator interface in Java can be used to sort a 2D array. Here's an easy example
import java.util.Arrays;
import java.util.Comparator;
public class Sort2DArray {
public static void main(String[] args) {
int[][] twoDArray = {
{4, 3, 2, 1},
{8, 7, 6, 5},
{12, 11, 10, 9}
};
System.out.println("Original 2D Array:");
print2DArray(twoDArray);
// Sorting the 2D array based on the first column
Arrays.sort(twoDArray, Comparator.comparingInt(a -> a[0]));
System.out.println("\nSorted 2D Array based on the first column:");
print2DArray(twoDArray);
}
// Helper method to print the 2D array
private static void print2DArray(int[][] array) {
for (int[] row : array) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
}
}
The Arrays.sort method is used to sort the 2D array in this example. The Comparator.comparingInt(a -> a[0]) method specifies that the array be sorted by the values in the first column. You can change the comparator to sort on other columns or according to your specific needs.
Take note that the array is sorted in ascending order in this example. Comparator.comparingInt(a -> a[0]) can be used to sort in descending order.Instead, use reversed(). Depending on your sorting criteria, adjust the comparator as needed.