Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

Sorting 2D array of strings in Java

I know that this question might have been asked before, but I was not able to find a fit answer. So say I have this array:

String[][] theArray = {
        {"james", "30.0"},
        {"joyce", "35.0"},
        {"frank", "3.0"},
        {"zach", "34.0"}};

Is there a way to descendingly sort this array by the second element of each sub-element. So I would get something like this.

theArray = {
        {"joyce", "35.0"},
        {"zach", "34.0"},
        {"james", "30.0"},
        {"frank", "3.0"}};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...