按值对 ObservableList 对象进行排序 Java

Map*_*SVK 4 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 changeAttendanceButton;
ImageView attendanceImage;
ImageView photo;
Run Code Online (Sandbox Code Playgroud)

字段“状态”可以有 2 个值:1. 存在,2. 不存在

然后我有可观察列表:

private ObservableList<Student> allStudentsWithStatus = FXCollections.observableArrayList();
Run Code Online (Sandbox Code Playgroud)

所以我将学生存储在这个列表中。每个学生都有在场或缺席的状态。

我需要按状态对这个 ObservableList 进行排序。我希望目前状态的学生在该列表中名列前茅。

有小费吗?

我将不胜感激任何帮助。

koz*_*zmo 5

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

\n
class StudentComparator implements Comparator<Student> {\n  @Override\n  public int compare(Student student1, Student student2) {\n      return student1.getStatus()\n               .compareTo(student2.getStatus());\n  }\n  //Override other methods...\n}\n
Run Code Online (Sandbox Code Playgroud)\n

或像这样创建

\n
Comparator<Student> studentComparator = Comparator.comparing(Student::getStatus);\n
Run Code Online (Sandbox Code Playgroud)\n

然后使用一个:

\n
ObservableList<Student> allStudentsWithStatus = ...\n
Run Code Online (Sandbox Code Playgroud)\n
Collections.sort(allStudentsWithStatus, studentComparator);\n
Run Code Online (Sandbox Code Playgroud)\n

或像这样使用

\n
allStudentsWithStatus.sort(studentComparator);\n
Run Code Online (Sandbox Code Playgroud)\n

2.使用SortedList ( javafx.collections.transformation.SortedList<E>):

\n
SortedList<Student> sortedStudents = new SortedList<>(allStudentsWithStatus, studentComparator);\n
Run Code Online (Sandbox Code Playgroud)\n

3.使用Stream APIComparator,如果您需要其他操作或需要收集到其他Collection (最慢的方式)

\n
allStudentsWithStatus.stream()\n        .sorted(Comparator.comparing(i -> i.getStatus()))\n        //other actions\n        //.filter(student -> student.getLastName().equals("\xd0\x98\xd0\xb2\xd0\xb0\xd0\xbd\xd0\xbe\xd0\xb2"))\n        .collect(Collectors.toList());\n        //.collect(Collectors.toSet());\n
Run Code Online (Sandbox Code Playgroud)\n