Comparator
Comparator is an interface used to define custom sorting logic for objects, separately from the class itself. Unlike Comparable, you can create multiple different Comparator implementations to sort the same class in different ways.
1. What is Comparator?
Comparator is an interface used to define custom sorting logic for objects, separately from the class itself. Unlike Comparable, you can create multiple different Comparator implementations to sort the same class in different ways.
2. Why is it used?
Sometimes you need to sort the same type of object in more than one way — like sorting students by marks in one place, and by name in another. Comparator allows this flexibility without changing the original class.
3. Real-Life Example
Think of a bookshelf that can be reorganized differently depending on the situation — sometimes by title, sometimes by author, sometimes by publication year — without changing anything about the books themselves. Comparator provides this kind of flexible, external sorting rule.
4. Syntax
javaComparator<DataType> comparatorName = new Comparator<DataType>() { public int compare(DataType a, DataType b) { // comparison logic } };
5. Example Program
javaimport java.util.*; class Student { String name; int marks; Student(String name, int marks) { this.name = name; this.marks = marks; } } public class ComparatorDemo { public static void main(String[] args) { List<Student> students = new ArrayList<>(); students.add(new Student("Riya", 85)); students.add(new Student("Aman", 70)); Comparator<Student> byName = (a, b) -> a.name.compareTo(b.name); Collections.sort(students, byName); for (Student s : students) { System.out.println(s.name + ": " + s.marks); } } }
Output:
Aman: 70
Riya: 856. Key Points to Remember
Comparatoris defined outside the class being sorted, allowing multiple different sorting strategies.- It's commonly written using a lambda expression for brevity, as shown above.
- Use
Comparablefor a single default sort order; useComparatorwhen multiple sort orders are needed.