0% completed
The Comparator interface in Java provides a way to define custom orderings for objects. It allows you to sort collections in an order that may differ from their natural ordering or when the objects do not implement the Comparable interface. By implementing Comparator, you can write flexible and reusable sorting logic that can be passed to methods like Collections.sort()
.
The Comparator interface is declared in the java.util
package as follows:
public interface Comparator<T> { int compare(T o1, T o2); }
compare(T o1, T o2)
method compares two objects of type T
. It returns:
o1
is less than o2
.o1
is equal to o2
.o1
is greater than o2
.In this example, we create an anonymous inner class that implements the Comparator interface to sort a list of strings based on their length.
Example Explanation:
lengthComparator
is defined using an anonymous inner class that implements Comparator<String>
.compare()
method subtracts the length of s2
from s1
, effectively sorting the list in ascending order of string length.Collections.sort(names, lengthComparator)
.In this example, we implement a custom Comparator using an anonymous inner class to sort a list of integers in descending order.
Example Explanation:
descendingComparator
is defined using an anonymous inner class that implements Comparator<Integer>
.compare()
method, the difference b - a
ensures that the larger integer is considered "less" for sorting purposes, resulting in descending order.Collections.sort(numbers, descendingComparator)
.The Comparator interface enables custom sorting of objects by providing a single method, compare()
, which defines the desired order.
By mastering the Comparator interface, you can control how collections are sorted, allowing you to tailor the order of elements to meet specific requirements without modifying the underlying objects.
.....
.....
.....