0Pricing
Java Academy · Lesson

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

  1. The Comparable Interface
  2. Comparator and Lambda Sorting
  3. Multi-Key Sorting with thenComparing
  4. Sorting Arrays and Collections in Practice
← Back to Java Academy