Skip to content

Commit 542a790

Browse files
committed
feat(ComparatorVsComparableDemo): add demo comparing Comparable vs Comparator
What - Added Student class implementing Comparable<Student>: - Natural ordering defined: GPA descending, then Name ascending. - compareTo(Student other) first compares GPA (higher first), then name. - toString() overridden for readable output. - Added ComparatorVsComparableDemo class with main method: - Created list of Student objects (Charlie, Bob, Alice, Akshit). - Demonstrated three sorting approaches: 1. Using Comparable (Collections.sort) → GPA desc, Name asc. 2. Using Comparator → sort by Name ascending. 3. Using Comparator with chaining → GPA ascending, then Name descending. Why - Demonstrates clear difference between Comparable and Comparator. - Provides educational example with both natural ordering and flexible custom orderings. - Shows practical usage of Comparator.comparing(), comparingDouble(), and thenComparing(). How - Comparable: - compareTo implemented in Student → defines single natural ordering. - Used Collections.sort(students) with no comparator. - Comparator: - Used list.sort(Comparator.comparing(s -> s.name)) for name ascending. - Used list.sort(Comparator.comparingDouble(s -> s.gpa).thenComparing(...)) for GPA asc, Name desc. - Printed results after each sort to verify differences. Logic - Inputs: list of students with GPA and names. - Outputs: - After Comparable: [Akshit (3.9), Bob (3.7), Alice (3.5), Charlie (3.5)]. - After Comparator (Name asc): [Akshit, Alice, Bob, Charlie]. - After Comparator (GPA asc, Name desc): [Charlie (3.5), Alice (3.5), Bob (3.7), Akshit (3.9)]. - Flow: 1. Natural order sort via Comparable. 2. Custom order sort by name via Comparator. 3. Another custom sort by GPA asc, then name desc. - Edge cases: - Students with identical GPA and name → treated as equal by compareTo. - Complexity / performance: O(n log n) sort. - Concurrency / thread-safety: Not thread-safe; local list only. - Error handling: Not needed here. Real-life applications - Comparable: best when there’s one canonical ordering (IDs, dates, scores). - Comparator: flexible for multi-criteria sorting in UIs, reports, or user-specified orders. - Useful in databases, ranking systems, and sorting utilities. Notes - Comparable provides a single natural order hardcoded into the class. - Comparator provides external, pluggable strategies, allowing multiple sort orders without modifying the class. - Comparator chaining (thenComparing) simplifies multi-field sorting. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent fff036f commit 542a790

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
package Package1;
2+
3+
import java.util.*;
4+
5+
// Student implements Comparable → defines natural ordering
6+
class Student implements Comparable<Student> {
7+
String name;
8+
double gpa;
9+
10+
public Student(String name, double gpa) {
11+
this.name = name;
12+
this.gpa = gpa;
13+
}
14+
15+
// Natural ordering → GPA descending, then name ascending
16+
@Override
17+
public int compareTo(Student other) {
18+
int gpaComparison = Double.compare(other.gpa, this.gpa);
19+
if (gpaComparison != 0) return gpaComparison;
20+
return this.name.compareTo(other.name);
21+
}
22+
23+
@Override
24+
public String toString() {
25+
return "{name='" + name + "', gpa=" + gpa + "}";
26+
}
27+
}
28+
29+
public class ComparatorVsComparableDemo {
30+
public static void main(String[] args) {
31+
List<Student> students = new ArrayList<>();
32+
students.add(new Student("Charlie", 3.5));
33+
students.add(new Student("Bob", 3.7));
34+
students.add(new Student("Alice", 3.5));
35+
students.add(new Student("Akshit", 3.9));
36+
37+
// Using Comparable (natural ordering)
38+
Collections.sort(students);
39+
System.out.println("Sorted by Comparable (GPA desc, Name asc): " + students);
40+
41+
// Using Comparator (custom ordering → Name only, ascending)
42+
students.sort(Comparator.comparing(s -> s.name));
43+
System.out.println("Sorted by Comparator (Name asc): " + students);
44+
45+
// Another Comparator → GPA ascending, then Name descending
46+
students.sort(Comparator
47+
.comparingDouble((Student s) -> s.gpa)
48+
.thenComparing(Comparator.comparing((Student s) -> s.name).reversed()));
49+
System.out.println("Sorted by Comparator (GPA asc, Name desc): " + students);
50+
}
51+
}
52+
53+
/*
54+
1. Comparable:
55+
- Defined inside the class using compareTo().
56+
- Provides "natural ordering" of objects.
57+
- Only ONE natural order can exist per class.
58+
- Example here: GPA descending, then Name ascending.
59+
60+
2. Comparator:
61+
- External object or lambda passed when sorting.
62+
- Allows multiple different sorting logics without changing the class.
63+
- Can be chained (thenComparing).
64+
- Example here:
65+
a) By Name ascending
66+
b) By GPA ascending, then Name descending
67+
68+
3. Key Differences:
69+
70+
| Aspect | Comparable | Comparator |
71+
|------------------|------------------------------------|-------------------------------------|
72+
| Package | java.lang | java.util |
73+
| Method | compareTo(Object o) | compare(Object o1, Object o2) |
74+
| Location | Inside the class itself | Separate class / lambda / method ref|
75+
| Ordering Count | One natural order per class | Multiple custom orders possible |
76+
| Usage | Collections.sort(list) | list.sort(Comparator) / TreeSet(c) |
77+
78+
4. When to Use:
79+
- Comparable → If there is a single, natural way to compare objects (e.g., GPA for students, ID for employees).
80+
- Comparator → If you need flexible or multiple ways to sort (by GPA, by name, by age, etc.).
81+
*/

0 commit comments

Comments
 (0)