Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📘 Lesson  ·  Lesson 42

Comparable vs Comparator in Java

In this lesson: Sort custom objects in Java with Comparable and Comparator — compareTo vs compare — examples with output. In Hindi & English.

Sorting your own objects

Java can sort numbers and strings on its own, but to sort your own objects (like Students) it needs to know the order. Two tools do this: Comparable (one built-in natural order) and Comparator (many custom orders). Together they give full control over sorting.

💡 Comparable = one default order inside the class. Comparator = extra custom orders outside it.

Comparable — natural order

class Student implements Comparable<Student> {
    String name; int marks;
    Student(String n, int m) { name = n; marks = m; }
    public int compareTo(Student other) {
        return this.marks - other.marks;   // sort by marks
    }
}
// use:
Collections.sort(studentList);   // uses compareTo

Implementing Comparable and its compareTo gives a class one natural order. Collections.sort then sorts a list using it. Here students sort by marks, low to high.

Comparator — custom orders

import java.util.Comparator;

Comparator<Student> byName = new Comparator<>() {
    public int compare(Student a, Student b) {
        return a.name.compareTo(b.name);   // sort by name
    }
};
Collections.sort(studentList, byName);

A Comparator defines a sort order outside the class, with its compare method. You pass it to sort. This lets you sort the same objects in different ways.

Many sort orders

The big advantage of Comparator is having several orders for the same class:

  • Sort students by marks (Comparable's natural order).
  • Sort by name (a Comparator).
  • Sort by marks descending (another Comparator).

Comparable gives the single default; Comparators give as many alternatives as you need.

Comparator with lambda

// short lambda form:
studentList.sort((a, b) -> a.marks - b.marks);

// even cleaner with a helper:
studentList.sort(Comparator.comparing(s -> s.name));

Because Comparator has a single method, you can write it as a short lambda. Comparator.comparing(...) makes it even cleaner by naming the field to sort by.

Comparable vs Comparator

PointComparableComparator
MethodcompareTocompare
WhereInside the classOutside the class
OrdersOne (natural)Many custom
Sort callCollections.sort(list)sort(list, comparator)

Common mistakes

  • Wrong compareTo return. Return negative/zero/positive, not true/false.
  • Integer overflow with subtraction. For very large ints, prefer Integer.compare(a, b).
  • Expecting many orders from Comparable. It gives one — use Comparators for more.
  • Not implementing the interface. Sorting objects needs Comparable or a Comparator.

Summary

  • Sorting custom objects needs Comparable or Comparator.
  • Comparable defines one natural order via compareTo.
  • Comparator defines custom orders via compare, outside the class.
  • Use Comparators for multiple sort orders.
  • Comparators can be written as short lambdas.

Next, keep data sorted with TreeSet, or write compact logic with lambda expressions.

Frequently Asked Questions

What is the difference between Comparable and Comparator?
Comparable defines one natural sort order inside the class itself (using compareTo). Comparator defines sorting outside the class (using compare), and you can make many different Comparators for different orders. Comparable is the default; Comparator adds flexibility.
What is the compareTo method?
compareTo is the single method in the Comparable interface. It returns a negative number, zero, or a positive number to say whether this object is less than, equal to, or greater than another — which tells the sort the order.
When should I use Comparator instead of Comparable?
Use Comparator when you need more than one sort order (for example, sort students by name and also by marks), or when you cannot change the class to add Comparable. Comparator keeps the sorting logic separate.
How do I sort a list of objects in Java?
If the class implements Comparable, call Collections.sort(list). To sort by a custom order, pass a Comparator: Collections.sort(list, comparator) or list.sort(comparator).
Can I write a Comparator as a lambda?
Yes. Since Comparator has a single method, you can write it as a lambda, like (a, b) -> a.marks - b.marks, or use helpers like Comparator.comparing(...) for clean, short sorting code.
← Back to Java Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicJava 8 Features Your progress: 42 / 61 (69%) · Lesson 43 / 61 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free