Category: java
Comparable
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:
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:
Collections.sort(list, new NameComparator());
Explanation
Example of sorting Student objects by name using
Comparator.
Code:
Explanation
Code:
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:
Collections.sort(list, (s1, s2) -> s1.name.compareTo(s2.name));