Different types of Comparator Techniques in Java
Table of Contents
-
Comparator Techniques in Java
Comparator Techniques in Java
Java provides robust mechanisms for comparing objects through the Comparable and Comparator interfaces.
a. Using Comparable Interface
The Comparable interface allows objects of a class to be compared using their natural order.
Example:
public class Product implements Comparable<Product> {
private String name;
private double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
@Override
public int compareTo(Product other) {
return Double.compare(this.price, other.price);
}
}b. Using Comparator Interface
For custom comparison logic, the Comparator interface is more flexible.
Example:
import java.util.*;
Comparator nameComparator = (p1, p2) -> p1.getName().compareTo(p2.getName());
List products = Arrays.asList(new Product("Apple", 1.2), new Product("Banana", 0.5));
products.sort(nameComparator);Best Practices
Use
Comparablefor natural ordering.Use
Comparatorfor multiple sorting criteria.
Table of Contents
-
Comparator Techniques in Java