Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort ObservableList Objects by Their Value Java

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.

like image 657
Michal Moravik Avatar asked Oct 25 '25 03:10

Michal Moravik


1 Answers

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());
like image 60
kozmo Avatar answered Oct 26 '25 16:10

kozmo