Home >Java >javaTutorial >How to Sort a 2D Array in Java Using Arrays.sort?
Sorting a 2D Array Using Arrays.sort
Sorting a multidimensional array can be a complex task. However, using Java's Arrays.sort method, it is possible to achieve this efficiently.
Specifically, the solution involves using the overloaded Arrays#Sort(T[] a, Comparator c) method, which takes a Comparator as its second argument. A comparator is an object that defines how objects are compared. In this case, we want to compare the values of the first element in each subarray.
To implement this, create a comparator that implements the java.util.Comparator interface and overrides its compare() method. This method should compare the first elements of the two arrays and return -1, 0, or 1 depending on the order they should appear.
For instance, consider the following 2D array:
double[][] myArr = { {1, 5}, {13, 1.55}, {12, 100.6}, {12.1, .85} };
To sort this array in ascending order based on the values of the first element in each subarray, use the following code:
java.util.Arrays.sort(myArr, new java.util.Comparator<double[]>() { public int compare(double[] a, double[] b) { return Double.compare(a[0], b[0]); } });
This will produce the following sorted array:
[ {1, 5}, {12, 100.6}, {12.1, .85}, {13, 1.55} ]
In Java 8 and later, you can use lambdas to simplify the comparator:
Arrays.sort(array, Comparator.comparingDouble(o -> o[0]));
The above is the detailed content of How to Sort a 2D Array in Java Using Arrays.sort?. For more information, please follow other related articles on the PHP Chinese website!