Java 按值对ObservableList对象进行排序

Java 按值对ObservableList对象进行排序,java,arrays,sorting,javafx,Java,Arrays,Sorting,Javafx,我有一个班级的学生,他有以下字段: private int id; private String firstName; private String lastName; private String imageLink; private String email; private String status; private String fullName; private int classId; private int percentage; Button changeAttendanc

我有一个班级的学生,他有以下字段:

private int id;
private String firstName;
private String lastName;
private String imageLink;
private String email;
private String status;
private String fullName;
private int classId;  
private int percentage;
Button changeAttendanceButton;
ImageView attendanceImage;
ImageView photo;
“状态”字段可以有2个值:1。现在,2。缺席

然后我有一个可观察的列表:

private ObservableList<Student> allStudentsWithStatus = FXCollections.observableArrayList();
private observeList allStudentsWithStatus=FXCollections.observearraylist();
所以我将学生存储在这个列表中。每个学生都有出席或缺席状态

我需要按状态对这个可观察列表进行排序。我希望现在的学生排在第一位

有什么建议吗


如果有任何帮助,我将不胜感激

1.您可以创建自定义比较器:

class StudentComparator implements Comparator<Student> {
  @Override
  public int compare(Student student1, Student student2) {
      return student1.getStatus()
               .compareTo(student2.getStatus());
  }
  //Override other methods if need to
}
或者像这样使用

Comparator<Student> studentComparator = Comparator.comparing(Student::getStatus);
allStudentsWithStatus.sort(studentComparator);
2.使用(
javafx.collections.transformation.SortedList
):


使用
List.sort(Comparator)
方法以及相应的
Comparator
。所谓适当,我指的是一个基于
状态
返回值的
比较器
。另外,由于您使用的是
可观察列表
,请看一看。具体来说,您只需执行
allStudentsWithStatus.sort(Comparator.comparing(Student::getStatus))
即可对列表进行排序,或者执行
SortedList sortedstatus=new SortedList(allStudentsWithStatus,Comparator.comparing(Student::getStatus))。在这两种情况下,将
Comparator.comparing(Student::getStatus)
替换为
Comparator.comparing(Student::getStatus).reversed()
以反转顺序。主题外,但我不确定为什么要对具有两个可能值的对象使用
字符串,顺便说一句,为什么不使用
布尔值
?谢谢@James\u,它能工作!我想在以后添加:“尚未提交”状态。那么
enum
仍然比
字符串更合适,不是吗?
Collections.sort(allStudentsWithStatus, studentComparator);
allStudentsWithStatus.sort(studentComparator);
SortedList<Student> sortedStudents = new SortedList<>(allStudentsWithStatus, studentComparator);
allStudentsWithStatus.stream()
        .sorted(Comparator.comparing(i -> i.getStatus()))
        //other actions
        //.filter(student -> student.getLastName().equals("Иванов"))
        .collect(Collectors.toList());
        //.collect(Collectors.toSet());