Sorting a List of integers based on a List of strings in Java

5377037 :

I have a Data Set something like this:

85 [Italy, France]    
95 [Italy]
91 [Israel, Jordan]
85 [France, Italy, Switzerland]
80 [USA]
84 [Mongolia, China]
95 [Antarctica]
84 [African Union]
82 [Argentina]
95 [Tibet, Nepal]
...

Which I have sorted based on based on the integers using below code (defining the class model):

public class Wonder implements Comparable<Wonder> {
    int hostility;
    List<String> countries;
    //some other data members

    //constructor
    //getters

    @Override
    public int compareTo(Wonder other) {
        if(hostility == other.hostility) {
            return 0;
        } else if(hostility < other.hostility) {
            return -1;
        } else if(hostility > other.hostility) {
            return 1;
        } else {
            return 0;
        }
    }
}

Sorting Code (PS: getAllData method will return a list of wonders, loading from Text file):

List<Wonder> wonders = getAllData(filePath);
wonders.sort((c1,c2)->c1.compareTo(c2));
Collections.reverse(wonders); // ordering highest to lowest 

After sorting the Data Set (sorted based on integers) looks something like this:

95 [Antarctica]
95 [Italy]
95 [Tibet, Nepal]
91 [Israel, Jordan]
85 [France, Italy, Switzerland]
85 [Italy, France]
84 [Mongolia, China]
84 [African Union]
82 [Argentina]
80 [USA]
...

Now, there is need to sort newly generated Data Set to alphabetically which are the List of countries (strings). For example, in new Data Set there're two records with the same integer 84 (1st integer has country Mongolia and 2nd integer has country African Union), so the second record should come first as African Union is alphabetically before the Mongolia.

...
84 [African Union]
84 [Mongolia, China]
...

Question: How to sort a List of integers based on a List of strings?

Avi :

You can further specialize the compareTo function to enact a secondary comparison. I'm assuming that every list contains at least one country; if such is not the case, you must handle empty lists. The altered compareTo is as so:

@Override
public int compareTo(Wonder other) {
    if(this == other) {
        return 0;
    } else if(hostility < other.hostility) {
        return -1;
    } else if(hostility > other.hostility) {
        return 1;
    } else {
        return -countries.get(0).compareTo(other.countries.get(0));
    }
}

Alternatively you may be looking for this:

wonders.sort(Comparator.comparingInt(Wonder::getHostility).reversed()
    .thenComparing(wonder -> wonder.getCountries().get(0)));
//don't reverse afterwards!

according to @Andrew's style

A repl.it with the best of all answers

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=126100&siteId=1
Recommended