📘 Lesson  ·  Lesson 41

Comparable vs Comparator

Two Ways to Sort Objects

To sort custom objects, Java uses Comparable (natural order, one way) or Comparator (custom orders, many ways).

Comparison

ComparableComparator
compareTo() in the classcompare() in a separate class
one sorting ordermultiple custom orders

Comparator Example

List<String> names = new ArrayList<>(List.of("Riya","Aman","Zoya"));
names.sort(Comparator.naturalOrder());     // A-Z
names.sort(Comparator.reverseOrder());     // Z-A
System.out.println(names);

Summary

  • Comparable: built into the class via compareTo() (one order).
  • Comparator: external, allows multiple custom sort orders.

Objects Sort करने के दो तरीके

Custom objects sort करने को Java Comparable (natural order, एक तरीका) या Comparator (custom orders, कई तरीके) use करता है।

तुलना

ComparableComparator
class में compareTo()अलग class में compare()
एक sorting orderकई custom orders

Comparator Example

List<String> names = new ArrayList<>(List.of("Riya","Aman","Zoya"));
names.sort(Comparator.naturalOrder());     // A-Z
names.sort(Comparator.reverseOrder());     // Z-A
System.out.println(names);

सारांश

  • Comparable: class में compareTo() से (एक order)।
  • Comparator: external, कई custom sort orders allow करता है।
← 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.