Custom Comparators
Introduction to Custom Comparators
Custom Comparators provide flexible sorting strategies when the default natural ordering is insufficient or unavailable.
Creating a Basic Comparator
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Collections;
import java.util.List;
public class ProductSorter {
static class Product {
String name;
double price;
Product(String name, double price) {
this.name = name;
this.price = price;
}
}
public static void main(String[] args) {
List<Product> products = new ArrayList<>();
products.add(new Product("Laptop", 1200.0));
products.add(new Product("Smartphone", 800.0));
products.add(new Product("Tablet", 500.0));
// Sort by price using anonymous Comparator
Collections.sort(products, new Comparator<Product>() {
@Override
public int compare(Product p1, Product p2) {
return Double.compare(p1.price, p2.price);
}
});
}
}
Comparator Types
flowchart TD
A[Comparator Types] --> B[Anonymous Class]
A --> C[Lambda Expression]
A --> D[Separate Comparator Class]
Comparator Methods Comparison
Method |
Description |
Use Case |
compare() |
Defines custom sorting logic |
Complex sorting requirements |
reversed() |
Reverses existing comparator |
Descending order sorting |
thenComparing() |
Adds secondary sorting criteria |
Multi-level sorting |
Advanced Comparator Techniques
// Lambda-based Comparator
Collections.sort(products, (p1, p2) ->
Double.compare(p1.price, p2.price));
// Multiple field sorting
Comparator<Product> multiFieldComparator =
Comparator.comparing((Product p) -> p.price)
.thenComparing(p -> p.name);
Collections.sort(products, multiFieldComparator);
Practical Comparator Patterns
- Sorting by Multiple Fields
- Reverse Ordering
- Null-Safe Comparisons
Lambda and Method Reference Approaches
// Method Reference
Collections.sort(products, Comparator.comparing(Product::getPrice));
// Reverse Order
Collections.sort(products, Comparator.comparing(Product::getPrice).reversed());
- Prefer method references over anonymous classes
- Use
Comparator
utility methods for complex sorting
- Minimize object creation during comparison
Best Practices
- Keep comparator logic simple and clear
- Handle potential null values
- Consider performance implications
- Use built-in Comparator methods when possible
At LabEx, we recommend mastering Custom Comparators to create more flexible and powerful sorting mechanisms in Java applications.