简体   繁体   中英

Sort a List of objects by one of it`s fields (that contains list of Strings)

I have a List of objects. Inside it I have another List of Strings (that contains numbers).

How can I order the List of objects, by the the numbers, that inside the List of Strings ?

I tried to do something like that:

 Collections.sort(bets, new Comparator<Bet>() {
       public int compare(Bet b1, Bet b2) {
             return Integer.valueOf(b1.getPlayersHighScores().get(0))
        .compareTo(Integer.valueOf(b2.getPlayersHighScores().get(0)));
       }
 });
 Collections.reverse(bets);

The main problem is that the List of bets may have one or more bets, but the List of getPlayersHighScores can contain many Strings .

First of all, why is the highscore a String if it contain a Number? Wouldn't it make more sense to make it Integer or some other Number?

Second, why do you keep a list of highscores? Doesn't it make more sense to retain only one highscore (the highest)?

Thirdly, by what property of the List of highscores would you order the Bets? As you've observed, just taking the first highscore for each bet doesn't make much sense. Would you want to order them by the max of each list? The sum? The avg?

Say you're going with sum, you then would only have to write you comparator something like (Java8):

new Comparator<Bet>() {
    public int compare(Bet b1, Bet b2) {
           return b1.getPlayersHighScores().stream().mapToInt(Integer::valueOf).sum()
            .compareTo(b2.getPlayersHighScores()stream().mapToInt(Integer::valueOf).sum());
         }
    }

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