Search code examples
javalistsortingoopencapsulation

How to sort a list by a private field?


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?


Solution

  • You have these options:

    1. make grade visible
    2. define a getter method for grade
    3. define a Comparator inside Student
    4. make Student implement Comparable
    5. use reflection (in my opinion this is not a solution, it is a workaround/hack)

    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:

    • You can easily define several Comparators
    • It is not much code
    • Your field stays private and encapsulated

    Example 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:

    • This defines, that sorting by grade represents the natural order of students
    • Some preexisting methods will automatically sort (like TreeMap)