How to create a custom sorting rule in Java?

To customize the sorting order, you can implement the Comparator interface. This interface includes a compare method for defining custom sorting rules.

Here is an example: let’s say we have a Student class with attributes for name and age, and we want to sort the Student objects in descending order by age.

import java.util.Comparator;

public class Student {
    private String name;
    private int age;
    
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public String getName() {
        return name;
    }
    
    public int getAge() {
        return age;
    }
}

public class AgeComparator implements Comparator<Student> {
    @Override
    public int compare(Student s1, Student s2) {
        if (s1.getAge() < s2.getAge()) {
            return 1;
        } else if (s1.getAge() > s2.getAge()) {
            return -1;
        } else {
            return 0;
        }
    }
}

Then, when using it, you can pass the AgeComparator into the Collections.sort method, allowing you to sort the Student objects according to the custom sorting rules.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        students.add(new Student("Alice", 20));
        students.add(new Student("Bob", 22));
        students.add(new Student("Charlie", 18));
        
        Collections.sort(students, new AgeComparator());
        
        for (Student student : students) {
            System.out.println(student.getName() + " - " + student.getAge());
        }
    }
}

The running result will display student information in descending order of age.

bannerAds