Sorting a 2D array based on first column


I am looknig to sort the following array based on the values of [][0]
double[][] myArr = new double[mySize][2];
so for ex, myArr contents is:
1      5
13     1.55
12     100.6
12.1   .85
I want it to get to :
1      5
12     100.6
12.1   .85
13     1.55

Best:
Arrays.sort(myArr, (a, b) -> Double.compare(a[0], b[0]));

Solution1: For integer array

// Function to sort by column
public static void sortbyColumn(int arr[][], int col)
{
// Using built-in sort function Arrays.sort
Arrays.sort(arr, new Comparator<int[]>() {

@Override
// Compare values according to columns
public int compare(final int[] entry1,
final int[] entry2) {

// To sort in descending order revert
// the '>' Operator
if (entry1[col] > entry2[col])
return 1;
else
return -1;
}
}); // End of function call sort().
}



Solution 2: For Double

double[][] array= {
{1, 5},
{13, 1.55},
{12, 100.6},
{12.1, .85} };

java.util.Arrays.sort(array, new java.util.Comparator<double[]>() {
    public int compare(double[] a, double[] b) {
        return Double.compare(a[0], b[0]);
    }
});

Solution 3:

Welcome Java 8:
Arrays.sort(myArr, (a, b) -> Double.compare(a[0], b[0]));

Solution 4:

Simplified Java 8
IntelliJ suggests to simplify the top answer to the:
Arrays.sort(queries, Comparator.comparingDouble(a -> a[0]));

Sources: 

Comments

Popular Posts