Course contentsShow
← Java
Lesson 1356 of 2,87030. Comparable and ComparatorFree lesson

Sorting Collections with Comparators

Using Collections.sort() with custom Comparator implementations to control element ordering.

Sorting Collections with Comparators

What You'll Learn

You'll learn how to sort List collections using Collections.sort() with custom Comparator implementations to control the order of elements.

The Core Idea

When you have a List and want to sort it in a specific order, you call Collections.sort() and pass it your list along with a Comparator. The Comparator defines the ordering rules—whether that's alphabetical, numerical, reverse order, or based on complex criteria involving multiple fields.

Think of it like giving sorting instructions to a librarian: "Sort these books by publication year, then by title." The Comparator is those instructions, and Collections.sort() is the librarian who follows them.

Using Collections.sort() with a Comparator

The method signature is:

Collections.sort(List<T> list, Comparator<? super T> comparator)

You provide the list you want sorted and a Comparator that knows how to compare two elements. The method modifies the list in place—it doesn't return a new list.

Here's a simple example sorting strings by length:

List<String> words = new ArrayList<>(Arrays.asList("apple", "pie", "banana", "kiwi"));

Collections.sort(words, Comparator.comparingInt(String::length));

System.out.println(words); // [pie, kiwi, apple, banana]

You can use any Comparator approach you've learned: lambda expressions, method references, factory methods like comparing(), or even chained comparators with thenComparing():

Collections.sort(people, 
    Comparator.comparing(Person::getLastName)
              .thenComparing(Person::getFirstName));

Key Takeaway: Collections.sort() sorts a List in place using any Comparator you provide, giving you complete control over element ordering without needing to modify the element class itself.