📘 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
| Comparable | Comparator |
|---|---|
| compareTo() in the class | compare() in a separate class |
| one sorting order | multiple 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 करता है।
तुलना
| Comparable | Comparator |
|---|---|
| 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 करता है।
💻 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.