Comparator and Lambda Sorting
Create Comparator instances with lambda expressions and Comparator.comparing factory methods.
Comparator and Lambda Sorting
Comparator<T> defines an external ordering for objects. Unlike Comparable, you can create as many Comparators as needed without modifying the class.
Creating Comparators
Create a Comparator with a lambda or method reference and pass it to sort methods.
import java.util.*;
record Product(String name, double price, int stock) {}
List<Product> products = new ArrayList<>(List.of(
new Product("Mouse", 29.99, 50),
new Product("Laptop", 999.00, 5),
new Product("USB Hub", 24.99, 100)
));
// Lambda comparator
products.sort((a, b) -> Double.compare(a.price(), b.price()));
System.out.println(products);
// [USB Hub, Mouse, Laptop] (by price ascending)All lessons in this course
- The Comparable Interface
- Comparator and Lambda Sorting
- Multi-Key Sorting with thenComparing
- Sorting Arrays and Collections in Practice