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.
Comparable
interface defines natural ordering using the compareTo()
method, but sometimes you need custom ordering, such as:Comparator
interface has a method called compare()
that allows us to define custom comparison logic.compare()
MethodThe Comparator
interface requires us to implement the compare()
method, which takes two objects as parameters and returns an integer:
compare(Object obj1, Object obj2)
:obj1
should be placed after obj2
.obj1
should be placed before obj2
.0
if both objects are considered equal.Comparator
Comparator<T>
interface.compare()
method, defining how two objects should be compared based on your custom criteria (e.g., descending order by price).Collections.sort()
or using it in data structures like TreeSet
.import java.util.Comparator;
import java.util.*;
class Product {
private String name;
private double price;
// Constructor
public Product(String name, double price) {
this.name = name;
this.price = price;
}
// Getters
public String getName() {
return name;
}
public double getPrice() {
return price;
}
// For better output
public String toString() {
return "Product{name='" + name + "', price=" + price + "}";
}
}
// Custom Comparator
// Comparator to sort by price in descending order
class PriceComparator implements Comparator<Product> {
public int compare(Product p1, Product p2) {
// Compare by price in descending order
return Double.compare(p2.getPrice(), p1.getPrice());
}
}
public class ProductSortingExample {
public static void main(String[] args) {
// Create a list of Product objects
List<Product> productList = new ArrayList<>();
productList.add(new Product("Laptop", 800.00));
productList.add(new Product("Smartphone", 500.00));
productList.add(new Product("Headphones", 50.00));
productList.add(new Product("Monitor", 300.00));
// Before sorting
System.out.println("Before Sorting by Price:");
for (Product p : productList) {
System.out.println(p);
}
// Sorting products by price in descending order using Comparator
Collections.sort(productList, new PriceComparator());
// After sorting
System.out.println("\nAfter Sorting by Price (Descending):");
for (Product p : productList) {
System.out.println(p);
}
}
}
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}
compare()
Method:p1
and p2
, by their price using Double.compare()
.Double.compare(p2.getPrice(), p1.getPrice())
: