Careeroza
Comparator
Many Orders for One Class
A Comparator<T> is a separate object that compares two values. Use it when you need several orders (by price, by rating) or when you cannot change the class.
| Comparable | Comparator | |
|---|---|---|
| Package | java.lang | java.util |
| Method | compareTo(T o) | compare(T a, T b) |
| Where | inside the class | outside the class |
| How many orders | one natural order | as many as you need |
| Used by | Collections.sort(list), TreeSet | list.sort(cmp), new TreeSet<>(cmp) |
Comparator Three Ways
Example
An anonymous class, a lambda, and the Comparator.comparing factory all produce the same result. (Lambdas and method references are covered in the Advanced level.)
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Product> products = new ArrayList<>(List.of(
new Product("Kettle", 1299, 4.2),
new Product("Mixer", 3499, 4.6),
new Product("Toaster", 999, 3.9)));
products.sort(new Comparator<Product>() { // 1. anonymous class
public int compare(Product a, Product b) {
return Integer.compare(a.price, b.price);
}
});
System.out.println("Price low-high : " + products);
products.sort((a, b) -> Double.compare(b.rating, a.rating)); // 2. lambda
System.out.println("Rating high-low: " + products);
products.sort(Comparator.comparing(p -> p.name)); // 3. factory
System.out.println("Name A-Z : " + products);
}
}
class Product {
final String name;
final int price;
final double rating;
Product(String name, int price, double rating) {
this.name = name;
this.price = price;
this.rating = rating;
}
public String toString() { return name; }
}Output
Price low-high : [Toaster, Kettle, Mixer] Rating high-low: [Mixer, Kettle, Toaster] Name A-Z : [Kettle, Mixer, Toaster]