Understanding Comparable and Comparator in Java
Understanding Comparable and Comparator in Java
In Java, sorting objects is important when working with collections like lists, sets, and maps. To sort
custom objects (like Student, Employee, Product, etc.), we use two interfaces:
Comparable Interface
Definition
Comparator Interface
Definition
• The sorting logic is outside the class in a separate class or lambda function.
Use Comparable when an object has a natural sorting order that never changes.
Use Comparator when sorting logic can change or when multiple sorting options are needed.
Scenario:
Imagine an e-commerce website where products are displayed in ascending order of price by
default.
package com.example.demo.compare;
import java.util.*;
@Override
public String toString() {
return id + " - " + name + " : $" + price;
}
}
Key Points:
Scenario:
Now, the e-commerce website allows users to sort products by Name or Price.
package com.example.demo.compare;
import java.util.*;
//Product class (without Comparable)
class Product {
int id;
String name;
double price;
@Override
public String toString() {
return id + " - " + name + " : $" + price;
}
}
// Sorting by Name
Collections.sort(products, new NameComparator());
System.out.println("Products sorted by Name:");
for (Product p : products) {
System.out.println(p);
}
Java 8+ allows sorting with lambda expressions, making Comparator even simpler.
Collections.sort(products, (p1, p2) -> p1.name.compareTo(p2.name)); // Sort by
Name
Key Points: