VOOZH about

URL: https://www.geeksforgeeks.org/java/comparable-vs-comparator-in-java/

⇱ Java Comparable vs Comparator - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java Comparable vs Comparator

Last Updated : 18 Aug, 2025

In Java, both Comparable and Comparator interfaces are used for sorting objects. The main difference between Comparable and Comparator is:

  • Comparable: It is used to define the natural ordering of the objects within the class.
  • Comparator: It is used to define custom sorting logic externally.

Example of Comparable

In this example, we use the Comparable interface to sort Movies by their release year using compareTo() method.


Output
Movies after sorting by year:
Star Wars 8.7 1977
Empire Strikes Back 8.8 1980
Return of the Jedi 8.4 1983

Explanation:

  • Movie implements Comparable<Movie> to define a default sort order.
  • compareTo() sorts movies by year in ascending order.
  • Collections.sort() uses compareTo() to perform the sorting.

Now, suppose we want to sort movies by their rating and names as well. When we make a collection element comparable (by having it implement Comparable), we get only one chance to implement the compareTo() method. The solution is using Comparator.

Example of Comparator

In this example, we use Comparator interface to define custom sorting logic to sort movies first by rating and then by name.


Output
Movies sorted by rating:
8.8 Empire Strikes Back 1980
8.7 Star Wars 1977
8.3 Force Awakens 2015

Movies sorted by name:
Empire Strikes Back 8.8 1980
Force Awakens 8.3 2015
Star Wars 8.7 1977

Explanation: In the above example, the Comparator interface is used to sort the movies first by rating and then by name. The Rating and NameCompare classes implement custom sorting logic. The Collections.sort() method uses these comparators to sort the list by multiple criteria.

Difference Between Comparable and Comparator

The table below demonstrates the difference between comparable and comparator in Java.

Features

Comparable

Comparator

Definition

It defines natural ordering within the class.

It defines external or custom sorting logic.

Method

compareTo()

compare()

Implementation

It is implemented in the class.

It is implemented in a separate class.

Sorting Criteria

Natural order sorting

Custom order sorting

Usage

It is used for a single sorting order.

It is used for multiple sorting orders.

Why comparator is a functional interface?

  • Functional Interface were introduced in Java 8. It has exactly one abstract method.
  • In Comparator<T>, the only abstract method is: int compare(T o1, T o2);
  • The equals(Object obj) method in Comparator comes from the Object class, so it is not abstract in the interface.
  • Therefore, Comparator qualifies as a functional interface and can be used with lambdas in Java 8+.
Comment