Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a list by a private field?

Tags:

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?

like image 946
Fanta Avatar asked Sep 03 '18 12:09

Fanta


People also ask

How do you sort a list of objects based on an attribute of the objects in Java 8?

Java 8 introduced a sort method in the List interface which can use a comparator. The Comparator. comparing() method accepts a method reference which serves as the basis of the comparison. So we pass User::getCreatedOn to sort by the createdOn field.

How do you sort elements in an ArrayList using comparable interface?

We can simply implement Comparator without affecting the original User-defined class. To sort an ArrayList using Comparator we need to override the compare() method provided by comparator interface. After rewriting the compare() method we need to call collections. sort() method like below.

How do you sort an array of objects based on a property in Java?

To sort an Object by its property, you have to make the Object implement the Comparable interface and override the compareTo() method. Lets see the new Fruit class again. The new Fruit class implemented the Comparable interface, and overrided the compareTo() method to compare its quantity property in ascending order.


1 Answers

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)
like image 80
slartidan Avatar answered Oct 14 '22 01:10

slartidan