简体   繁体   中英

Java sort 2D String Array by number value of third column

I'm given a text file with countries, names and scores of skating competitors. I have to read each line into an array, then sort the array in descending order.

I managed to get everything organized like this:

infoArray[0][0] = "GER";
infoArray[0][1] = "Nathalie WEINZIERL Maylin & Daniel Peter LIEBERS Nelli & Alexander";
infoArray[0][2] = "17.0";

infoArray[1][0] = "RUS";
infoArray[1][1] = "Evgeny PLYUSHCHENKO Tatiana & Maxim Yulia LIPNITSKAYA Ekaterina & Dmitri"
infoArray[1][2] = "37.0";

infoArray[2][0] = "CHN";
infoArray[2][1] = "Kexin ZHANG Han YAN Cheng & Hao Xintong & Xun"
infoArray[2][2] = "20.0"

And so on for 10 different countries.

What I need now is to display the 10 different countries by descending order using the third column, which is the numeric value (though it's in string format).

So in other words I want the output of those three countries to be:

RUS: 37.0
CHN: 20.0
GER: 17.0

I thought about using nested loops but can't quite grasp how I could get that to work.

Using Java 8, you can just create a Comparator using the respective column as the key for comparing and then reverse that comparator. This will sort the array in-place.

Arrays.sort(infoArray, 
            Comparator.comparing((String[] entry) -> Double.parseDouble(entry[2]))
                      .reversed());

Or for older versions of Java, create you own Comparator implementing compare :

Arrays.sort(infoArray, new Comparator<String[]>() {
    public int compare(String[] o1, String[] o2) {
        return Double.compare(Double.parseDouble(o2[2]), 
                              Double.parseDouble(o1[2]));
    }
});

However, as noted in comments it may be worth creating a class for those information items and having that class implement Comparable :

class Info implements Comparable<Info> {
    String nation;
    String names;
    double score;

    // more stuff ...

    public int compareTo(Info other) {
        return Double.compare(this.score, other.score);
    }
}

Then sort like this:

Arrays.sort(infoArray, Comparator.reverseOrder());

You can create a class and can set all the fields.In your case 3 fields will be there den either you can implement Comparable and in compareTo method you can write your own logic which will be dependent on numeric value and den you can sort it using Collections utility.

If you don't want to implement Comparable interface den you can write your own Comparator class and pass that to in Collections utility method that will do sort on the basis of your logic.

Please avoid using set collections if you have duplicates.

This is an XY Question because this is not the proper usage of a 2D array in Java. When using a collection or n-dimensional array in Java, the data within that data structure should always be of the same type (or at least within that type's inheritance hierarchy).

As Alexis C mentioned in his/her comment: Java is an Object Oriented language, and therefore you should be using objects of a class to contain the data. Then you can sort the structure on a particular field of that object.

Here's an example (I'm not exactly sure what the different components of the array actually represent:

class MyClass {
     private string countryCode;
     private string names;
     private double score;

     public MyClass() {
         countryCode = null;
         names = null;
         score = 0d;
     }

     public string getCountryCode() { return this.countryCode; }
     public void setCountryCode(string code) { this.countryCode = code; }
     //repeat the above pattern for names & score
}    

You can then add create an object and add data into it as such:

 MyClass data = new MyClass();
 data.setCountryCode("GER");
 data.setNames("Nathalie WEINZIERL Maylin & Daniel Peter LIEBERS Nelli & Alexander");
 data.setScore(17.0);

This data can be added to a collection such as an ArrayList and that can be sorted.

List<MyClass> myDataCollection = new ArrayList<>();
myDataCollection.add(data);
//repeat for each object to populate the list

//sort the collection
Collections.sort(myDataCollection, Comparator.comparingDouble(s -> s.getScore()).reversed());

Keep in mind that this example is for Java 8. This allows for us to use a lambda expression instead of creating an explicit comparator.

I think I would just make a new list, containing only the scores. Then sort this score list. And then replacing the scores with the related array (containing country, name, score)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM