Java Intermediate

0% completed

Previous
Next
Understanding the Comparator Interface

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); }
  • Explanation:
    The compare(T o1, T o2) method compares two objects of type T. It returns:
    • A negative integer if o1 is less than o2.
    • Zero if o1 is equal to o2.
    • A positive integer if o1 is greater than o2.

Examples

Example 1: Sorting Strings by Their Length

In this example, we create an anonymous inner class that implements the Comparator interface to sort a list of strings based on their length.

Java
Java

. . . .

Example Explanation:

  • Comparator Definition:
    • The lengthComparator is defined using an anonymous inner class that implements Comparator<String>.
    • The compare() method subtracts the length of s2 from s1, effectively sorting the list in ascending order of string length.
  • Sorting Operation:
    • The list of names is sorted using Collections.sort(names, lengthComparator).
  • Outcome:
    • The output shows the list sorted from the shortest string to the longest string.

Example 2: Sorting Integers in Descending Order

In this example, we implement a custom Comparator using an anonymous inner class to sort a list of integers in descending order.

Java
Java

. . . .

Example Explanation:

  • Comparator Definition:
    • The descendingComparator is defined using an anonymous inner class that implements Comparator<Integer>.
    • In the compare() method, the difference b - a ensures that the larger integer is considered "less" for sorting purposes, resulting in descending order.
  • Sorting Operation:
    • The list of integers is sorted using Collections.sort(numbers, descendingComparator).
  • Outcome:
    • The final output displays the list sorted from highest to lowest.

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.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next