Sorting 排序可观察列表<;类别>;按值的升序和降序排列-JAVAFX
我有一个类,它有playerName和Score,我在我的Controller类中创建了这个类的observeList。玩家和分数将添加到此数组中。但问题是我如何根据分数对其进行排序Sorting 排序可观察列表<;类别>;按值的升序和降序排列-JAVAFX,sorting,javafx,observablelist,Sorting,Javafx,Observablelist,我有一个类,它有playerName和Score,我在我的Controller类中创建了这个类的observeList。玩家和分数将添加到此数组中。但问题是我如何根据分数对其进行排序 ObservableList<PlayerScore> playerScores = FXCollections.observableArrayList(); 通过实现一个比较器,然后对比较器实例使用sort方法,可以对数组进行排序 ()正如您根据给定标准对任何列表进行排序一样:使用,例如: //假设
ObservableList<PlayerScore> playerScores = FXCollections.observableArrayList();
通过实现一个比较器,然后对比较器实例使用sort方法,可以对数组进行排序
()正如您根据给定标准对任何列表进行排序一样:使用,例如:
//假设存在返回int的实例方法Class.getScore
//(当然,也可以使用comparator的其他实现)
Comparator Comparator=Comparator.comparingInt(类::getScore);
如果(!stateASC.isSelected()){
比较器=比较器。反转();
}
排序(playerScores,comparator);
顺便说一句:
Class
对于类名来说是一个糟糕的选择,因为名称与java.lang.Class
冲突,我不明白为什么要使用typeClass
。你能解释一下吗?这只是一个例子,类的真实名称是PlayerScores。我现在已经更新了问题。
//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
}
// 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);