The Comparator interface in Java is used to define custom sorting orders for objects, especially when you need multiple sorting strategies or cannot modify the original class. Unlike Comparable, which defines a class’s natural ordering, Comparator externalizes the comparison logic, making it more flexible and reusable.

Key Features of Comparator:

  • Functional Interface: Can be used with lambda expressions and method references.

  • Core Method: int compare(T o1, T o2) returns a negative, zero, or positive integer based on whether o1 is less than, equal to, or greater than o2.

  • Static Factory Methods (Java 8+):

    • Comparator.comparing(Function keyExtractor) – creates a comparator based on a property (e.g., User::getAge).

    • Comparator.comparingInt, comparingDouble, comparingLong – optimized for primitive types.

  • Chaining Comparators:

    • thenComparing() – applies a secondary sort when primary keys are equal.

    • reversed() – reverses the current comparator’s order.

    • reverseOrder() – returns a comparator that reverses natural ordering.

Example Usage:

List<User> users = List.of(new User("Alice", 30), new User("Bob", 25));
// Sort by age ascending
users.stream().sorted(Comparator.comparing(User::getAge)).forEach(System.out::println);

// Sort by age descending, then by name
users.stream()
     .sorted(Comparator.comparing(User::getAge).reversed()
                      .thenComparing(User::getName))
     .forEach(System.out::println);

Best Practices:

  • Use Comparator when sorting objects without modifying their source code.

  • Ensure comparators are consistent with equals to avoid unexpected behavior in TreeSet or TreeMap.

  • Implement Serializable if used in serializable collections.

Note: Comparator is part of java.util and has been enhanced in Java 8 with functional programming features, making it a cornerstone for modern Java sorting.

🌐
GeeksforGeeks
geeksforgeeks.org › java › stream-sorted-comparator-comparator-method-java
Stream sorted (Comparator comparator) method in Java - GeeksforGeeks
December 26, 2025 - In Java, the Stream.sorted(Comparator comparator) method sorts the elements of a stream based on a provided Comparator and returns a new sorted stream.
🌐
GitHub
github.com › frohoff › jdk8u-jdk › blob › master › src › share › classes › java › util › Comparator.java
jdk8u-jdk/src/share/classes/java/util/Comparator.java at master · frohoff/jdk8u-jdk
import java.util.Comparators; · /** * A comparison function, which imposes a <i>total ordering</i> on some · * collection of objects. Comparators can be passed to a sort method (such · * as {@link Collections#sort(List,Comparator) Collections.sort} or {@link ·
Author   frohoff
Discussions

Noob Programmer, ELI5: Comparators?
You can implement the Comparator method on a class in order to enable alternative sorting or searching methods through the java library. For instance, if you wanted to sort an ArrayList of type String based on String length, then you could write a class called StringLengthComparator that implements Comparator with the desired comparison. StringLengthComparator slc = new StringLengthComparator(); int result = slc.compare(a, b); If a is shorter than b, then the method would return a number less than zero. If it is longer than b, then it would return a number greater than zero. If they are the same length, then it would return zero. You could then sort the ArrayList using Collections.sort. Collections.sort(myArrayList, slc); More on reddit.com
🌐 r/java
17
1
October 23, 2014
6 Advanced Comparator and Comparable Examples in Java 8 for Sorting ArrayList Objects By Fields
That page has way too much breaking up the flow of the page, at least on mobile. It's somewhat ironic that the thumbnail doesn't use Comparator. Array.sort(testStrings, comparing(String::length)); More on reddit.com
🌐 r/java
1
13
September 15, 2021
java - When to use Comparable and Comparator - Stack Overflow
I have a list of objects I need to sort on a field, say Score. Without giving much thought I wrote a new class that implements Comparator, that does the task and it works. Now looking back at thi... More on stackoverflow.com
🌐 stackoverflow.com
Comparator vs Comparable
I mean they're different things so you can't just always use one or the other. A comparator is a bit of code that knows how to sort a type of object, making an object comparable is teaching the object how to sort sort its own type. If I'm making an object for use elsewhere in an application or for an external library it's way more convenient for everyone who works with it if the object knows how to sort itself reasonably. Creating a comparator that they also need to know about and pass into every attempt to sort your object is clumsy and fragile. Similarly if you're working with an object who you can't change the implementation of, a comparator allows you to sort those objects, or for times when the default comparable behavior won't work correctly you can use the custom comparator. They're different tools for different situations but most of the time when something needs sorted making the item comparable is the right first step. More on reddit.com
🌐 r/learnjava
3
3
April 26, 2021
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Comparator.html
Comparator (Java Platform SE 8 )
October 20, 2025 - A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order.
🌐
Reddit
reddit.com › r/java › noob programmer, eli5: comparators?
r/java on Reddit: Noob Programmer, ELI5: Comparators?
October 23, 2014 -

I know that there is http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html but I'm genuinely confused about them and would appreciate any english translation if at all possible.

I know that it contains the compare(blah, blah) method but how does that work?

Top answer
1 of 3
14
You can implement the Comparator method on a class in order to enable alternative sorting or searching methods through the java library. For instance, if you wanted to sort an ArrayList of type String based on String length, then you could write a class called StringLengthComparator that implements Comparator with the desired comparison. StringLengthComparator slc = new StringLengthComparator(); int result = slc.compare(a, b); If a is shorter than b, then the method would return a number less than zero. If it is longer than b, then it would return a number greater than zero. If they are the same length, then it would return zero. You could then sort the ArrayList using Collections.sort. Collections.sort(myArrayList, slc);
2 of 3
10
Coding time! Now let's assume we have a person class like this: public class Person { private String firstName = null; private String lastName = null; public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return this.firstName; } public String getLastName() { return this.lastName; } } And let's assume we want to store that person alphabetically by its last name. So we could write an comparator like this: import java.util.Comparator; public class PersonComparator implements Comparator { @Override public int compare(Person p1, Person p2) { return p1.getLastName().compareTo(p2.getLastName()); } @Override public boolean equals(Object obj) { return obj.equals(this); } } Finally we will store this in a collection of type ArrayList like this: ArrayList addressBook = new ArrayList<>(); addressBook.add(new Person("Christopher", "Nolan")); addressBook.add(new Person("JJ", "Abrams")); addressBook.add(new Person("David", "Lynch")); addressBook.add(new Person("Tim", "Burton")); Now if we list the address book with: for (Person p : addressBook) { System.out.println(p.getLastName() + ", " + p.getFirstName()); } we'll get an unsorted output: Nolan, Christopher Abrams, JJ Lynch, David Burton, Tim But luckily collections do come with a sorting mechanism. All we have to do is providing the logic for comparing two items: addressBook.sort(new PersonComparator()); and we get a sorted output: Abrams, JJ Burton, Tim Lynch, David Nolan, Christopher Now with Java 8 you even can skip the step of implementing a Comparator and simply use a lamda expression like this: addressBook.sort((Person p1, Person p2) -> p1.getLastName().compareTo(p2.getLastName())); Full example here . Note that there is a subreddit ( r/javahelp ) for questions like these! Happy coding.
🌐
Medium
medium.com › @ganesh.shah › comparator-vs-comparable-java-8-940a83f53bd3
Comparator vs Comparable | Java 8 | by GANESH SHAH | Medium
March 8, 2024 - Comparator vs Comparable | Java 8 In Java, Comparator and Comparable are interfaces used for sorting objects, but they serve different purposes: Comparable Interface: The Comparable interface is …
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-comparator-interface
Java Comparator Interface - GeeksforGeeks
The Comparator interface in Java is used to define custom sorting logic for objects. It belongs to java.util package allows sorting of objects of user-defined classes without modifying their source code.
Published   1 month ago
🌐
Medium
medium.com › @AlexanderObregon › javas-comparator-comparing-method-explained-342361288af6
Java’s Comparator.comparing() Method Explained | Medium
October 2, 2024 - Java’s Comparator.comparing() method is a powerful tool that simplifies custom sorting based on object properties. By allowing us to create comparators for sorting collections like lists, this method reduces the complexity of implementing ...
Find elsewhere
🌐
Codecademy
codecademy.com › docs › java › comparator
Java | Comparator | Codecademy
July 28, 2025 - Comparator in Java is an interface used to order objects of an arbitrary class. It is not to be confused with the Comparable interface, which is implemented by the class to be sorted.
🌐
Jenkov
jenkov.com › tutorials › java-collections › comparator.html
Java Comparator
October 4, 2020 - The Java Comparator interface, java.util.Comparator, represents a component that can compare two objects so they can be sorted using sorting functionality in Java. When sorting e.g a Java List you can pass a Java Comparator to the sorting method.
🌐
GeeksforGeeks
geeksforgeeks.org › java › sort-an-array-in-java-using-comparator
Sort an Array in Java using Comparator - GeeksforGeeks
July 23, 2025 - // Java program to sort list of integers // using Comparator in Java // Descending Order according to length import java.util.Comparator; import java.util.List; import java.util.Arrays; public class DescendingComparator implements Comparator<Integer> { @Override public int compare(Integer i1, Integer i2) { return i2 - i1; } public static void main(String[] args) { // Ceating an array of Integers Integer[] arr = {5, 20, 10, 3, 15}; // Converting Integer array to list List<Integer> list = Arrays.asList(arr); // Sorting list of integers in descending order List<Integer> numbers = list; numbers.sort(new DescendingComparator()); System.out.println(numbers); } }
🌐
Scaler
scaler.com › home › topics › java › comparable and comparator in java
Difference between Comparable and Comparator in Java - Scaler Topics
July 13, 2023 - Comparable and Comparator in Java allow us to define custom sorting behavior for objects, including sorting based on multiple data members.
🌐
Board Infinity
boardinfinity.com › blog › understanding-java-comparator-interface
How To Use Comparator In Java | Board Infinity
July 7, 2023 - The Java Comparator interface, java.util.Comparator, allows you to compare two objects in order to sort them using Java's sorting functionality. For example, if you want to sort a Java List, you can pass it to a Java Comparator.
🌐
InfoWorld
infoworld.com › home › blogs › java challengers
Sorting Java objects with Comparable and Comparator | InfoWorld
May 23, 2024 - Programmers frequently need to sort elements from a database into a collection, array, or map. In Java, we can implement whatever sorting algorithm we want with any type. Using the Comparable interface and compareTo() method, we can sort using alphabetical order, String length, reverse alphabetical order, or numbers.
🌐
freeCodeCamp
freecodecamp.org › news › comparable-vs-comparator-explained-in-java
Comparable vs Comparator Interfaces in Java – Which Should You Use and When?
July 23, 2024 - The Comparator interface in Java provides a way to define multiple ways of comparing and sorting objects. Unlike the Comparable interface, which allows only a single natural ordering, Comparator is designed to offer flexibility by allowing multiple ...
🌐
Coderanch
coderanch.com › t › 560667 › java › Understanding-Comparator
Understanding Comparator (Java in General forum at Coderanch)
December 4, 2011 - The code that would be calling compare() of the Comparator would either get a positive integer, zero or a negative integer. But how does it know what order(ascending/descending) it has to sort in? See the documentation of the Comparable.compareTo() method in Java API doc.
🌐
Mkyong
mkyong.com › home › java8 › java 8 lambda : comparator example
Java 8 Lambda : Comparator example - Mkyong.com
August 5, 2015 - In this example, we will show you how to use Java 8 Lambda expression to write a Comparator to sort a List.
🌐
PriorityQueue
nkamphoa.com › home › the comparator interface in java
The Comparator Interface in Java
November 24, 2025 - The Comparator interface is central to Java’s ordering and sorting capabilities. Unlike the Comparable interface, which defines natural ordering directly inside the class, a Comparator externalizes comparison logic.