Sorting ObservableList<Class> by value in ascending and descending order - JAVAFX

Java Gamer picture Java Gamer · Mar 25, 2016 · Viewed 15.8k times · Source

I have a Class which has playerName and Score, I have created a ObservableList of this class in my Controller class. Players and scores are added to this array. But the question is how do I sort it according to the score?

ObservableList<PlayerScore> playerScores = FXCollections.observableArrayList();

This is how it looks so far:

//stateACS is a toggle button
if (stateASC.isSelected()) {
    //Sort in asc order by player score
    FXCollections.sort(playerScores);
}else{
    //sort in desc order by player score

}

Answer

fabian picture fabian · Mar 25, 2016

Just the same way you sort any list by a given criterion: By using a Comparator, e.g.:

// assuming there is a instance method Class.getScore that returns int
// (other implementations for comparator could be used too, of course)
Comparator<Class> comparator = Comparator.comparingInt(Class::getScore); 
if (!stateASC.isSelected()) {
    comparator = comparator.reversed();
}
FXCollections.sort(playerScores, comparator);

BTW: Class is a poor choice for a class name because of the name clash with java.lang.Class.