creativecreatorormaybenot creativecreatorormaybenot - 5 months ago 24
Java Question

How to sort multidimensional string array by one column in integer value in java?

I have for example this multidimensional array:


String[][] array = new String[10][2];


In the first column I have strings which are in my case usernames, but in the second column I have strings which should represent integers. Now I want to sort the array like this:

Before:

Petter 543
John 276
Jay 1879
Alf 5021
etc.

After:

Alf 5021
Jay 1879
Petter 543
John 276
etc.


So I want the highest value at the top and the lowest at the bottom but don't mess up the names. All I found till now is how to sort bother all integer multidimensional arrays or only string multidimensional arrays and not how to just sort the second column based on just integers.

I once got it sorted but it was sorted in "alphabetic" way:

So 1000 was the highest score
12 was the second highest score and
999999 was the lowest score.

Like 1 represents "a" and 9 represents "z".

Answer

Using Java 8 streams:

String[][] out = Arrays.stream(names)
    .sorted(Comparator.comparing(x -> -Integer.parseInt(x[1])))
    .toArray(String[][]::new);