按值按升序和降序对ObservableList <class>进行排序 - JAVAFX

时间:2016-03-25 21:54:09

标签: sorting javafx observablelist

我有一个具有playerName和Score的Class,我在Controller类中创建了这个类的ObservableList。玩家和分数将添加到此阵列中。但问题是如何根据得分对其进行排序?

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

到目前为止它的表现如下:

//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

}

2 个答案:

答案 0 :(得分:5)

与按给定标准对任何列表排序的方式相同:使用Comparator,例如:

// 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因类名与java.lang.Class发生冲突而导致类名选择不佳。

答案 1 :(得分:0)

您可以通过实现Comparator然后将sort方法与Comparator实例一起使用来对数组进行排序。

https://docs.oracle.com/javase/8/javafx/api/javafx/collections/FXCollections.html#sort-javafx.collections.ObservableList-java.util.Comparator-