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.

ComparableComparator
Packagejava.langjava.util
MethodcompareTo(T o)compare(T a, T b)
Whereinside the classoutside the class
How many ordersone natural orderas many as you need
Used byCollections.sort(list), TreeSetlist.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]