Understanding the Comparator Interface

The Comparator interface in Java is used when you want to customize the sorting order of objects, rather than relying on their natural ordering (as defined by the Comparable interface). It allows you to create multiple ways to sort objects without modifying the class itself.

Key Points:

  • The Comparable interface defines natural ordering using the compareTo() method, but sometimes you need custom ordering, such as:
    • Sorting by a different field.
    • Sorting in descending order.
    • Sorting based on multiple fields (e.g., first by price, then by name).
  • The Comparator interface has a method called compare() that allows us to define custom comparison logic.

Comparator Interface: The compare() Method

The Comparator interface requires us to implement the compare() method, which takes two objects as parameters and returns an integer:

  • compare(Object obj1, Object obj2):
    • Returns positive (+ve) if obj1 should be placed after obj2.
    • Returns negative (-ve) if obj1 should be placed before obj2.
    • Returns 0 if both objects are considered equal.

Steps to Implement Comparator

  1. Create a class that implements the Comparator<T> interface.
  2. Override the compare() method, defining how two objects should be compared based on your custom criteria (e.g., descending order by price).
  3. Use this comparator to sort your objects by passing it to Collections.sort() or using it in data structures like TreeSet.
Code Example
Output
Before Sorting by Price:
Product{name='Laptop', price=800.0}
Product{name='Smartphone', price=500.0}
Product{name='Headphones', price=50.0}
Product{name='Monitor', price=300.0}

After Sorting by Price (Descending):
Product{name='Laptop', price=800.0}
Product{name='Smartphone', price=500.0}
Product{name='Monitor', price=300.0}
Product{name='Headphones', price=50.0}

Explanation of compare() Method:

  • We compare the two products, p1 and p2, by their price using Double.compare().
  • Double.compare(p2.getPrice(), p1.getPrice()):
    • This compares the prices in reverse order, so products with higher prices will appear first.
    • This is how we achieve descending order.