How can I sort a list of objects by a private field?

  • A+
Category:Languages

I have a class that looks like this:

public class Student {     private int grade;     // other fields and methods  } 

and I use it like this:

List<Student> students; 

How can I sort studentsList by grade, taking into account that it is a private field?

 


You have these options:

  1. make grade visible
  2. define a getter method for grade
  3. define an inner class for comparisions (like Comparator)
  4. make Student implement Comparable

Example for solution 3:

public class Student implements IStudent {     private int grade;      private 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 IStudent, 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); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: