I have a 2D-array that I want to sort based on the second column. The first column should remain paired with the second column.
The 2D-array is initially as follows (2×10 matrix):
0 10
1 9
2 9
3 9
4 15
5 10
6 4
7 8
8 11
9 12
I want the above 2D-array to be sorted like this:
4 15
9 12
8 11
0 10
5 10
1 9
2 9
3 9
7 8
6 4
Now, I’ve tried adapting the answer from: Sort a two dimensional array based on one column into this code:
Arrays.sort(theArray, new Comparator<Integer[]>()
{
@Override
public int compare(Integer[] int1, Integer[] int2)
{
Integer numOfKeys1 = int1[1];
Integer numOfKeys2 = int2[1];
return numOfKeys1.compareTo(numOfKeys2);
}
});
However, it doesn’t seem to sort the array at all. When printing the array after calling the sort() function the array is in its initial order.
I also tried adapting the answer from here: sorting 2D array of String in java but I encountered the same problem.
Have I made some fatal mistake when adapting these solutions, or should my code work?
Also, how would I go about sorting this array in descending order? Would I replace the return statement in compare() with this line?
return -numOfKeys2.compareTo(numOfKeys1);
Any help would be greatly appreciated. Thanks!
EDIT: Just posting the rest of my code to see if the problem is elsewhere.
public void Sort()
{
Integer[][] theArray = {{0,10},{1,9},{2,9},{3,9},{4,15},{5,10},{6,4},{7,8},{8,11},{9,12}};;
dump(theArray);
Arrays.sort(theArray, new Comparator<Integer[]>()
{
@Override
public int compare(Integer[] int1, Integer[] int2)
{
Integer numOfKeys1 = int1[1];
Integer numOfKeys2 = int2[1];
return numOfKeys1.compareTo(numOfKeys2);
}
});
System.out.println("====");
dump(theArray);
}
public void dump(Integer[][] array)
{
for(int p = 0, q = 10; p < q; p++)
{
System.out.println(array[p][0] + " " + array[p][1]);
}
}
EDIT 2:
I’ve got it working. Thanks everyone for your help. I had multiple Sort() functions (an older one that wasn’t working, and the one you see above), and it turns out I was calling the wrong one, even though I thought I changed the call. Just one of those days.
Feel free to use the code above if you want to sort an array. It’s fully working now.
It works fine for me. To reverse order you’d negate the original
compareTo, or swap the variables, but not both.We’ll probably need to see the rest of the code to understand why you’re seeing what you’re seeing; I cut and pasted your code verbatim, so odds are good the issue lies elsewhere.