cogm
cogm

Reputation: 285

Sorting an Array List of Arrays

I'm reading game scores from a text file into an ArrayList. Each item in the ArrayList is a String array with 2 indexes, one stores the player's name and the other the score.

What's the best way from here to sort the list into numerical order by the score, in order to display high scores?

Thanks!

Upvotes: 0

Views: 151

Answers (2)

yts
yts

Reputation: 1890

It should look something like this, assuming the score is stored in index 1:

Collections.sort(playerList, new Comparator<String[]>(){
   @Override
   public int compare(String[] player1, String[] player2) {
         return Integer.parseInt(player1[1]) - Integer.parseInt(player2[1]);
     }
 }

playerList is the list of your arrays. This method will sort the array list for you using the supplied Comparator object which, as you see, takes two elements from the ArrayList and supplies a method of determining which one is first.

Upvotes: 3

Tom
Tom

Reputation: 17567

If you're not forced to use an array to store the score, then I recommend using a dedicated model class for it, that implements the Comparable interface.

public class Score implements Comparable<Score> {
    final String name;
    final int score;

    public Score(String name, int score) {
        this.name = name;
        this.score = score;
    }

    @Override
    public int compareTo(final Score that) {
        return that.score - this.score;
    }

    @Override
    public String toString() {
        return String.format("Score[name=%s, score=%d]", name, score);
    }
}

The current implementation sorts descending. If you want to sort ascending, then change it to return this.score - that.score;.

You can use that class like this:

public static void main(String[] args) {
    final List<Score> scores = new ArrayList<>();
    scores.add(new Score("Mike", 100));
    scores.add(new Score("Jenny", 250));
    scores.add(new Score("Gary", 75));
    scores.add(new Score("Nicole", 110));

    Collections.sort(scores);

    for (final Score score : scores) {
        System.out.println(score);
    }
}

The output will be:

Score[name=Jenny, score=250]
Score[name=Nicole, score=110]
Score[name=Mike, score=100]
Score[name=Gary, score=75]

Upvotes: 3

Related Questions