Hackforge Academy

Category: React • Beginner

Published on 18 Feb 2026

Explanation

Comparator is an interface in the java.util package used to define custom sorting logic for objects. It is used when you want multiple sorting strategies.

Code Example

public interface Comparator<T> {
    int compare(T o1, T o2);
}

Explanation

Comparator is used to sort objects based on different fields such as name, salary, or age without modifying the original class.

Code Example

Collections.sort(list, new NameComparator());

Explanation

Example of sorting Student objects by name using Comparator.

Code Example


Explanation

Code Example

import java.util.*;
class Student {
    int id;
    String name;
    Student(int id, String name) {
        this.id = id;
        this.name = name;
    }
}
class NameComparator implements Comparator<Student> {
    public int compare(Student s1, Student s2) {
        return s1.name.compareTo(s2.name);
    }
}

Explanation

Comparator can also be implemented using lambda expressions in Java 8 and above.

Code Example

Collections.sort(list, (s1, s2) -> s1.name.compareTo(s2.name));

Want structured learning with real projects?

Join our Weekend Live Workshop and become job-ready faster.