Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an Arraylist by two fields (Java)

Tags:

java

arraylist

I have an arraylist of highscores for a card game I am making. There needs to be a finite limit on the number of scores this arraylist can store, which the user of the system may define (let's say 10 for now). The fields in the objects in the arraylist are the player's name (string), their score (int) and a (almost) unique ID for the player (Long, System.currentTimeMillis()). The arraylist should be sorted by the score, where the lowest score is the best. However, if all players in the arraylist have the same score and a new player is added with that score, I would like the players with the most recent scores (the ones for whom the ID is highest) to be stored before the older ones, so the older ones are discarded.

Essentially I need a way to sort an ArrayList by two fields- score first, low to high, then if the scores match sort those by the ID. Removing excess elements I already have mostly covered, although if there is a way to integrate that I would be interested to hear it.

EDIT: I'm trying to sort an Arraylist of objects with those attributes, not a single arraylist with them just thrown in. My bad.

like image 508
4oursword Avatar asked Dec 19 '22 04:12

4oursword


1 Answers

If you use Java 8, there is a neat way of nesting comparators with method references:

List<Player> players = // ...

players.sort(Comparator
    .comparing(Player::getScore)
    .thenComparing(Player::getId));

More information can be found in the Comparator JavaDoc.

like image 91
matsev Avatar answered Dec 31 '22 03:12

matsev