Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java Arrays.sort 2d array

I am looking to sort the following array based on the values of [][0]

double[][] myArr = new double[mySize][2]; 

so for example, 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 

I am looking to do this without having to implement my own sort.

like image 976
Dax Durax Avatar asked Mar 16 '13 17:03

Dax Durax


People also ask

Can we sort a 2D array in Java?

In a 2D array, a cell has two indexes one is its row number, and the other is its column number. Sorting is a technique for arranging elements in a 2D array in a specific order. The 2D array can be sorted in either ascending or descending order.

How do you sort elements in a 2D array?

Make the 2D array into a separate simple (1D) array (STEP 1). Then use the Arrays. sort() method to sort the simple array (STEP 2). Then set each space of the 2D array to be the number of columns across (X-coordinate where the space will be changed) multiplied by the number of spaces per row in the 2D array.


2 Answers

Use Overloaded Arrays#Sort(T[] a, Comparator c) which takes Comparator as the second argument.

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]);     } }); 

JAVA-8: Instead of that big comparator, we can use lambda function as following-

Arrays.sort(array, Comparator.comparingDouble(o -> o[0])); 
like image 152
PermGenError Avatar answered Oct 22 '22 20:10

PermGenError


Welcome Java 8:

Arrays.sort(myArr, (a, b) -> Double.compare(a[0], b[0])); 
like image 33
Marsellus Wallace Avatar answered Oct 22 '22 21:10

Marsellus Wallace