Nearby lessons

88 of 125

Java - Comparable vs Comparator

📌 What You Will Learn
  • What the Collection Framework is and why we need it
  • List, Set, Map and Queue — the four big families
  • Choosing the right collection for the right job
  • Comparable vs Comparator
  • The internal working of HashMap (interview favourite)

Comparable vs Comparator is a core concept of the Java language. This lesson explains Sorting — Comparable vs Comparator with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

Sorting — Comparable vs Comparator

To sort your own objects, you use either Comparable or Comparator.

  • Comparable — the class itself decides its natural sorting order. Override compareTo(). Collections.sort(list) uses it.
  • Comparator — a separate class decides a custom order (like sorting by marks instead of name). Pass it to Collections.sort(list, comparator).

Comparable vs Comparator — Comparison Table

PointComparableComparator
Where it livesInside the class itself (natural order)Separate class/lambda (custom order)
MethodcompareTo()compare()
Sort callCollections.sort(list)Collections.sort(list, cmp)
Multiple orderings?Only one natural orderMany custom orders possible
Packagejava.langjava.util
Example01
JCode Cell
1class Student implements Comparable<Student> {
2 int rollNo;
3 String name;
4 int marks;
5 Student(int r, String n, int m) { rollNo = r; name = n; marks = m; }
6 
7 public int compareTo(Student o) { // natural order: by rollNo
8 return this.rollNo - o.rollNo;
9 }
10 public String toString() { return rollNo + " " + name + " " + marks; }
11}
12 
13class Demo {
14 public static void main(String[] args) {
15 List<Student> list = new ArrayList<>();
16 list.add(new Student(103, "Anil", 80));
17 list.add(new Student(101, "Rahul", 90));
18 list.add(new Student(102, "Priya", 85));
19 
20 Collections.sort(list); // by rollNo (Comparable)
21 System.out.println("By rollNo: " + list);
22 
23 Comparator<Student> byMarks = (s1, s2) -> s2.marks - s1.marks; // lambda
24 Collections.sort(list, byMarks); // custom: marks desc
25 System.out.println("By marks: " + list);
26 }
27}
Output
By rollNo: [101 Rahul 90, 102 Priya 85, 103 Anil 80] By marks: [101 Rahul 90, 102 Priya 85, 103 Anil 80]
📝 Key Takeaways
  • Collection is an interface; Collections is a utility class with static helpers.
  • List = ordered, allows duplicates. Set = no duplicates. Map = key-value pairs. Queue = FIFO.
  • ArrayList is the everyday list; HashMap is the everyday map.
  • HashMap works on hashCode + buckets; collisions chain, then become trees (Java 8+).
  • Comparable (compareTo) is the natural order; Comparator (compare) gives custom order.
  • Always override equals() and hashCode() together for your own objects.
  • Collections.sort() and Collections.reverse() are the handy helpers.

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1