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 whethero1is less than, equal to, or greater thano2.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
Comparatorwhen sorting objects without modifying their source code.Ensure comparators are consistent with equals to avoid unexpected behavior in
TreeSetorTreeMap.Implement
Serializableif used in serializable collections.
Note:
Comparatoris part ofjava.utiland has been enhanced in Java 8 with functional programming features, making it a cornerstone for modern Java sorting.
Videos
Noob Programmer, ELI5: Comparators?
6 Advanced Comparator and Comparable Examples in Java 8 for Sorting ArrayList Objects By Fields
java - When to use Comparable and Comparator - Stack Overflow
Comparator vs Comparable
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?
Use Comparable if you want to define a default (natural) ordering behaviour of the object in question, a common practice is to use a technical or natural (database?) identifier of the object for this.
Use Comparator if you want to define an external controllable ordering behaviour, this can override the default ordering behaviour.
See also:
- Sorting an ArrayList of objects using a custom sorting order
I would say that an object should implement Comparable if that is the clear natural way to sort the class, and anyone would need to sort the class would generally want to do it that way.
If, however, the sorting was an unusual use of the class, or the sorting only makes sense for a specific use case, then a Comparator is a better option.
Put another way, given the class name, is it clear how a comparable would sort, or do you have to resort to reading the javadoc? If it is the latter, odds are every future sorting use case would require a comparator, at which point the implementation of comparable may slow down users of the class, not speed them up.