![]() |
VOOZH | about |
The Comparator interface in Java is used to define custom sorting logic for objects. It belongs to java.util package allows sorting of objects of user-defined classes without modifying their source code. It is especially useful when:
class MyComparator implements Comparator<Type> {
public int compare(Type obj1, Type obj2) {
// comparison logic
}
}
1 Amit 2 Rahul
Explanation:
The Collections.sort() method arranges the elements of a List based on the rules defined by a Comparator.
public static <T> void sort(List<T> list, Comparator<? super T> c)
The method uses the compare() function of the given Comparator to decide the order of elements. The compare() method compares two elements and returns:
Example: Sorting by Multiple Fields (Name, then Age)
Original List: Ajay : 27 Sneha : 23 Simran : 37 After Sorting: Ajay : 27 Simran : 37 Sneha : 23
Note: String comparison using compareTo() is case-sensitive, where uppercase letters are considered smaller than lowercase. For case-insensitive sorting, use compareToIgnoreCase() or Comparator.comparing(String::toLowerCase).
Java 8 introduced a more simple way to write comparators using lambda expressions. We can use the method mentioned below for achieving same result:
students.sort(
Comparator.comparing(Student::getName)
.thenComparing(Student::getAge)
);
Original List: Ajay : 27 Sneha : 23 Simran : 37 After Sorting: Ajay : 27 Simran : 37 Sneha : 23