Home >Java >javaTutorial >How to Sort a 2D Array in Java by the Values in the First Column?
Sorting 2D Array based on First Column Values using Java Arrays.sort
In Java, sorting a 2D array based on the values of a specific column can be achieved using the overloaded Arrays.sort(T[] a, Comparator c) method that accepts a Comparator as its second argument.
Consider the following example, where we have a 2D array myArr containing pairs of doubles:
double[][] myArr = new double[mySize][2]; // populate myArr with data
To sort this array based on the first column values, we can use the Comparator interface to define a custom comparison rule:
java.util.Comparator<double[]> comparator = new java.util.Comparator<double[]>() { public int compare(double[] a, double[] b) { return Double.compare(a[0], b[0]); } };
We can then pass this Comparator to the Arrays.sort method:
java.util.Arrays.sort(myArr, comparator);
Alternatively, in Java 8 or later, we can use a lambda function instead of the anonymous inner class for the Comparator:
Arrays.sort(myArr, Comparator.comparingDouble(o -> o[0]));
After sorting, the myArr will be sorted based on the values in the first column. The result will be:
[ {1.0, 5.0}, {12.0, 100.6}, {12.1, 0.85}, {13.0, 1.55} ]
The above is the detailed content of How to Sort a 2D Array in Java by the Values in the First Column?. For more information, please follow other related articles on the PHP Chinese website!