Sorting 2D array of strings in Java

Use Arrays.sort(arr, comparator) with a custom comparator:

Arrays.sort(theArray, new Comparator<String[]>(){

    @Override
    public int compare(final String[] first, final String[] second){
        // here you should usually check that first and second
        // a) are not null and b) have at least two items
        // updated after comments: comparing Double, not Strings
        // makes more sense, thanks Bart Kiers
        return Double.valueOf(second[1]).compareTo(
            Double.valueOf(first[1])
        );
    }
});
System.out.println(Arrays.deepToString(theArray));

Output:

[[joyce, 35.0], [zach, 34.0], [james, 30.0], [frank, 23.0]]


Beware:

you will be sorting the array you passed in, Arrays.sort() will not return a new array (in fact it returns void). If you want a sorted copy, do this:

String[][] theCopy = Arrays.copyOf(theArray, theArray.length);

And perform the sorting on theCopy, not theArray.

Leave a Comment