My entity class looks like this:
public class Student {
private int grade;
// other fields and methods
}
and I use it like that:
List<Student> students = ...;
How can I sort students
by grade
, taking into account that it is a private field?
You have these options:
grade
visiblegrade
Comparator
inside Student
Student
implement Comparable
Example for solution 3
:
public class Student {
private int grade;
public static Comparator<Student> byGrade = Comparator.comparing(s -> s.grade);
}
and use it like this:
List<Student> students = Arrays.asList(student2, student3, student1);
students.sort(Student.byGrade);
System.out.println(students);
This is my favorite solution because:
Comparator
sExample of solution 4
:
public class Student implements Comparable {
private int grade;
@Override
public int compareTo(Object other) {
if (other instanceof Student) {
return Integer.compare(this.grade, ((Student) other).grade);
}
return -1;
}
}
You can sort everywhere like this:
List<Student> students = Arrays.asList(student2, student3, student1);
Collections.sort(students);
System.out.println(students);
Aspects of this solution:
grade
represents the natural order of studentsTreeMap
)