I have a custom Java class which contains two variables: username
and score
.
I am looking to create an ArrayList with multiple of these inside. I then want to sort them in order of lowest to highest, based on the value of their score
Highscore.class
public class Highscore implements ConfigurationSerializable {
String username;
int score;
public Highscore(String username, int score) {
this.username = username;
this.score = score;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public Map<String, Object> serialize() {
Map<String, Object> mappedObject = new LinkedHashMap<String, Object>();
mappedObject.put("username", username);
mappedObject.put("score", score);
return mappedObject;
}
public static Highscore deserialize(Map<String, Object> mappedObject) {
return new Highscore((String) mappedObject.get("username"),
(int) mappedObject.get("score"));
}
}
For example, below shows the ArrayList containing multiple Highscore
's. I want to look only at the score
based on low to high, and then sort the Highscore
's into another ArrayList.
ArrayList<Highscore> highscores = new ArrayList<>();
highscores.add(new Highscore("user1", 10));
highscores.add(new Highscore("user2", 0));
highscores.add(new Highscore("user3", -15));
highscores.add(new Highscore("user4", 30));
highscores.add(new Highscore("user5", 5));
// Now, sort the highscores based on their 'score'
Thanks in advance.