Course contentsShow
← Java
Lesson 1220 of 2,87028. Collections Utility ClassFree lesson

Sorting with Natural Order vs Comparator

Understand when to rely on Comparable's natural order versus passing a Comparator to sort.

Sorting with Natural Order vs Comparator

What you'll learn: You'll understand when to use a class's built-in natural ordering versus when to provide your own custom sorting logic with a Comparator.


When you call Collections.sort(list), Java needs to know how to compare elements. There are two ways this happens:

Natural Order (Comparable)

Some classes have a natural order built into them — a default, obvious way to sort. When a class implements Comparable, it defines its own compareTo() method that establishes this natural order.

List<Integer> numbers = Arrays.asList(5, 2, 8, 1);
Collections.sort(numbers); // Uses natural order
// Result: [1, 2, 5, 8]

List<String> words = Arrays.asList("zebra", "apple", "mango");
Collections.sort(words); // Uses alphabetical order
// Result: [apple, mango, zebra]

Integers sort numerically, Strings sort alphabetically — these are their natural orders.

Custom Order (Comparator)

But what if you want to sort differently? Maybe you want Strings sorted by length instead of alphabetically, or numbers in descending order. That's when you pass a Comparator to Collections.sort():

List<String> words = Arrays.asList("zebra", "apple", "mango");
Collections.sort(words, (a, b) -> a.length() - b.length());
// Result: [apple, mango, zebra] (sorted by length)

List<Integer> numbers = Arrays.asList(5, 2, 8, 1);
Collections.sort(numbers, (a, b) -> b - a);
// Result: [8, 5, 2, 1] (descending order)

Think of it like this: Natural order is the default sorting you get "out of the box." A Comparator is like giving specific instructions: "No, this time sort by length, not alphabetically."

Key Takeaway: Use Collections.sort(list) when the natural order is what you want; use Collections.sort(list, comparator) when you need custom sorting logic that differs from the default behavior.