Sitemap
Liezel Shaw

Liezel Shaw

Software Engineer skilled in all things Java, Spring and AI, building tech solutions for companies and mentoring others to grow as developers.

Mastering the Comparator in Java: Writing Cleaner, Smarter, and More Flexible Sorting Logic

3 min readNov 10, 2025

--

Press enter or click to view image in full size

As developers, we often begin our journey sorting lists of numbers or strings — simple, straightforward tasks. But as our applications grow, so too does the complexity of how we need to order and compare objects. This is where Java’s Comparator shines.

Understanding Comparator not only helps you write cleaner and more maintainable code, it also strengthens your ability to reason about object behavior — a key skill for becoming a confident and highly capable software engineer.

Today, we’re going to take a deep dive into Comparator, explore where it differs from Comparable, and learn practical patterns that you’ll use over and over in real-world codebases.

Understanding the Need for Comparator

Consider a simple Person class:

public class Person {
private String name;
private int age;
// constructor, getters, toString...
}

Now imagine you have a list of Person objects and you need to sort them:

  • Sometimes by name
  • Sometimes by age
  • Sometimes by age then name
  • And sometimes in reverse order

If you try to bake this logic into the Person class itself, things get messy. And that’s exactly where Comparator becomes useful.

Comparator vs Comparable

Press enter or click to view image in full size

Use Comparable when there is a clear natural order (e.g., numbers ascending, alphabetical strings).

Get Liezel Shaw’s stories in your inbox

Join Medium for free to get updates from this writer.

Use Comparator when you need more flexibility.

Writing Your First Comparator

Let’s sort our list of Person objects by age.

Comparator<Person> compareByAge = new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return Integer.compare(p1.getAge(), p2.getAge());
}
};

Then use it:

Collections.sort(personList, compareByAge);

But modern Java offers something cleaner…

Comparator with Lambda

Comparator<Person> compareByAge = 
(p1, p2) -> Integer.compare(p1.getAge(), p2.getAge());

personList.sort(compareByAge);

Beautiful, right?

Comparator.comparing() — The Elegant Approach

Java 8 introduced a powerful helper method:

personList.sort(Comparator.comparing(Person::getAge));

This reads like English and keeps your code concise and intention-revealing.

Combining Comparators

Sorting by multiple fields is common. For example:

  • Sort by age, then name alphabetically
personList.sort(
Comparator.comparing(Person::getAge)
.thenComparing(Person::getName)
);

This is incredibly expressive and avoids messy nested comparisons.

Reversing Sort Order

Need descending order?

personList.sort(
Comparator.comparing(Person::getAge).reversed()
);

Or mix and match:

personList.sort(
Comparator.comparing(Person::getAge).reversed()
.thenComparing(Person::getName)
);

Dealing with Null Values

Sometimes data isn’t perfect — nulls happen.

Java has helpers for that:

personList.sort(
Comparator.comparing(Person::getName, Comparator.nullsLast(String::compareTo))
);

Options include:

  • Comparator.nullsFirst(...)
  • Comparator.nullsLast(...)

Real-World Example

Sorting API responses, UI tables, database DTOs — all common real-world cases. Consider a service returning product items:

public List<Product> getProductsSorted() {
return productRepo.findAll().stream()
.sorted(
Comparator.comparing(Product::getCategory)
.thenComparing(Product::getPrice)
)
.toList();
}

Notice how natural the sorting logic reads — this improves code readability and maintainability dramatically.

Final Thoughts: Growing as a Developer

Mastering Comparator is not just about syntax. It’s about learning to separate concerns, keeping your domain objects clean, and writing expressive, intention-revealing code.

Good developers write code that works.
Great developers write code that reads well and adapts well.

And today, you took another step toward being great. Keep going. You’re growing — one concept at a time.

--

--

Liezel Shaw
Liezel Shaw