Issue
I have a class Student with these fields:
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;
Field "status" can have 2 values: 1. present, 2. absent
Then I have Observable List:
private ObservableList<Student> allStudentsWithStatus = FXCollections.observableArrayList();
So I store Students in this list. Each student has either present or absent status.
I need to SORT this ObservableList by status. I want students with present status be first in that list.
Any tips?
I would be grateful for any help.
Solution
1.You can create custom Comparator:
class StudentComparator implements Comparator<Student> {
@Override
public int compare(Student student1, Student student2) {
return student1.getStatus()
.compareTo(student2.getStatus());
}
//Override other methods...
}
or create like this
Comparator<Student> studentComparator = Comparator.comparing(Student::getStatus);
and then use one:
ObservableList<Student> allStudentsWithStatus = ...
Collections.sort(allStudentsWithStatus, studentComparator);
or use like this
allStudentsWithStatus.sort(studentComparator);
2.Use SortedList (javafx.collections.transformation.SortedList<E>
):
SortedList<Student> sortedStudents = new SortedList<>(allStudentsWithStatus, studentComparator);
3.Use Stream API and Comparator, if you need to other actions or need to collect to other Collection (the slowest way):
allStudentsWithStatus.stream()
.sorted(Comparator.comparing(i -> i.getStatus()))
//other actions
//.filter(student -> student.getLastName().equals("Иванов"))
.collect(Collectors.toList());
//.collect(Collectors.toSet());
Answered By - kozmo
Answer Checked By - Pedro (JavaFixing Volunteer)