Comparator and Lambda Sorting
Create Comparator instances with lambda expressions and Comparator.comparing factory methods.
Comparator and Lambda Sorting is a free Java Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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)Comparator.comparing Factory
Comparator.comparing(keyExtractor) creates a Comparator from a key extractor function — cleaner than raw lambdas.
import java.util.Comparator;
Comparator<Product> byPrice = Comparator.comparingDouble(Product::price);
Comparator<Product> byName = Comparator.comparing(Product::name);
Comparator<Product> byStock = Comparator.comparingInt(Product::stock);
products.sort(byPrice);
System.out.println(products); // sorted by price ascending
products.sort(byName);
System.out.println(products); // sorted alphabeticallyreversed()
reversed() inverts the order of any comparator.
import java.util.Comparator;
Comparator<Product> mostExpensiveFirst =
Comparator.comparingDouble(Product::price).reversed();
products.sort(mostExpensiveFirst);
System.out.println(products);
// [Laptop($999.0), Mouse($29.99), USB Hub($24.99)]naturalOrder and reverseOrder
Comparator.naturalOrder() uses the class's Comparable. reverseOrder() inverts it.
List<String> names = new ArrayList<>(List.of("Charlie", "Alice", "Bob"));
names.sort(Comparator.naturalOrder());
System.out.println(names); // [Alice, Bob, Charlie]
names.sort(Comparator.reverseOrder());
System.out.println(names); // [Charlie, Bob, Alice]
// Sort integers descending
List<Integer> nums = new ArrayList<>(List.of(5, 2, 8, 1, 9));
nums.sort(Comparator.reverseOrder());
System.out.println(nums); // [9, 8, 5, 2, 1]Null-Safe Comparators
Comparator.nullsFirst() and nullsLast() handle null elements without NPE.
import java.util.*;
List<String> withNulls = new ArrayList<>(Arrays.asList("Charlie", null, "Alice", null, "Bob"));
withNulls.sort(Comparator.nullsLast(Comparator.naturalOrder()));
System.out.println(withNulls); // [Alice, Bob, Charlie, null, null]
withNulls.sort(Comparator.nullsFirst(Comparator.naturalOrder()));
System.out.println(withNulls); // [null, null, Alice, Bob, Charlie]Stream sorted() with Comparator
Use the sorted() intermediate stream operation with a Comparator for functional-style sorting.
import java.util.stream.*;
record Employee(String name, String dept, double salary) {}
List<Employee> employees = List.of(
new Employee("Alice", "Engineering", 95000),
new Employee("Bob", "Marketing", 72000),
new Employee("Charlie", "Engineering", 105000)
);
// Sort by salary descending in a stream pipeline
employees.stream()
.sorted(Comparator.comparingDouble(Employee::salary).reversed())
.forEach(e -> System.out.println(e.name() + ": $" + e.salary()));
// Charlie: $105000.0 / Alice: $95000.0 / Bob: $72000.0Comparator as Lambda vs Method Reference
Method references make comparators even more concise when the key extractor is a simple getter.
// Lambda
Comparator<String> c1 = (a, b) -> a.length() - b.length();
// Comparator.comparing with lambda
Comparator<String> c2 = Comparator.comparing(s -> s.length());
// Comparator.comparingInt with method reference (cleanest)
Comparator<String> c3 = Comparator.comparingInt(String::length);
List<String> words = new ArrayList<>(List.of("banana", "fig", "apple", "kiwi"));
words.sort(c3);
System.out.println(words); // [fig, kiwi, apple, banana]Stateful Comparator
Although comparators should usually be stateless, you can inject configuration via constructor parameters.
class DistanceComparator implements Comparator<String> {
private final String target;
DistanceComparator(String target) { this.target = target; }
@Override
public int compare(String a, String b) {
return Integer.compare(distance(a), distance(b));
}
private int distance(String s) { return Math.abs(s.length() - target.length()); }
}
List<String> words = new ArrayList<>(List.of("Java", "Go", "Python", "C", "Kotlin"));
words.sort(new DistanceComparator("Java"));
System.out.println(words); // closest length to "Java" firstCustom Sort for Product Catalog
Sorting a product catalog by availability first, then price, then name.
import java.util.*;
record Item(String name, double price, boolean inStock) {}
List<Item> catalog = List.of(
new Item("Laptop", 999.0, true),
new Item("Case", 19.99, false),
new Item("Mouse", 29.99, true),
new Item("Monitor", 349.0, true)
);
Comparator<Item> catalogSort =
Comparator.comparing(Item::inStock).reversed() // in-stock first
.thenComparingDouble(Item::price) // then cheapest
.thenComparing(Item::name); // then alphabetical
catalog.stream().sorted(catalogSort)
.forEach(i -> System.out.printf("%s %-15s $%.2f%n",
i.inStock() ? "[Y]" : "[N]", i.name(), i.price()));Arrays.sort with Comparator
Arrays.sort(array, comparator) sorts object arrays with a custom comparator.
String[] words = {"banana", "fig", "apple", "kiwi", "cherry"};
// Sort by length, then alphabetically for same length
Arrays.sort(words,
Comparator.comparingInt(String::length)
.thenComparing(Comparator.naturalOrder()));
System.out.println(Arrays.toString(words));
// [fig, kiwi, apple, banana, cherry]Quick Check
What does Comparator.comparingDouble(Product::price).reversed() produce?
Recap: Comparator and Lambda Sorting
Key takeaways:
- Comparator
defines external ordering — use as many as needed - Comparator.comparing(keyExtractor) creates comparators from getters
- reversed() inverts any comparator; naturalOrder()/reverseOrder() for Comparable types
- nullsFirst() and nullsLast() handle null elements safely
- Use sorted(comparator) in Stream pipelines for functional-style ordering
- Comparators can be passed to sort(), Arrays.sort(), TreeSet, TreeMap
Frequently asked questions
Is the “Comparator and Lambda Sorting” lesson free?
Yes — the full text of “Comparator and Lambda Sorting” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.
What will I learn in “Comparator and Lambda Sorting”?
Create Comparator instances with lambda expressions and Comparator.comparing factory methods. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Java Academy?
No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Comparator and Lambda Sorting” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Java Academy lesson?
Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- The Comparable Interface
- Comparator and Lambda Sorting
- Multi-Key Sorting with thenComparing
- Sorting Arrays and Collections in Practice