5
$\begingroup$

I have a two dimensional double array. I need to sort my based column 1 in descending order. How can I sort my two dimensional array in descending order.

Sample data and code are the following:

package mypro.com; public class SortDoubleArrary { public static void main(String agrs[]) throws Exception{ double[][] testdatset=new double[5][2]; testdatset[0][0]=20.0; testdatset[0][1]=0.20; testdatset[1][0]=100.0; testdatset[1][1]=0.50; testdatset[2][0]=10.0; testdatset[2][1]=0.95; testdatset[3][0]=220.0; testdatset[3][1]=0.35; testdatset[4][0]=140.0; testdatset[4][1]=0.10; } } 

Expected output looks like the following

 10.0 0.95 100.0 0.5 220.0 0.35 20.0 0.2 140.0 0.1 
$\endgroup$

    1 Answer 1

    4
    $\begingroup$

    There is an overloaded sort method in java.util.Arrays class which takes two arguments: the array to sort and a java.util.Comparator object.

    You can add the following lines of code with your program to get the expected result.

    import java.util.Arrays; import java.util.Comparator; Arrays.sort(testdatset, new Comparator<double[]>() { @Override public int compare(double[] o1, double[] o2) { return Double.compare(o2[1], o1[1]); } }); 
    $\endgroup$

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.