Commit b26b112
committed
feat(StudentSortWithComparator): add comparator demo sorting students by GPA desc then Name asc
What
- Added StudentSortWithComparator class with:
- Local static Student class:
- Fields: name (String), gpa (double).
- Constructor and getters.
- Main method:
- Creates list of Student objects: Charlie (3.5), Bob (3.7), Alice (3.5), Akshit (3.9).
- Defines Comparator:
- Primary: GPA descending (Comparator.comparing(Student::getGpa).reversed()).
- Secondary: Name ascending (thenComparing(Student::getName)).
- Sorts list with comparator.
- Prints sorted list.
Why
- Demonstrates use of Comparator chaining for multi-level sorting.
- Highlights reversed() for descending order and thenComparing() for tie-breaking.
- Self-contained demo without requiring external Student class.
How
- Comparator created using fluent API:
- comparing(Student::getGpa) → sorts by GPA ascending.
- reversed() → switches to descending.
- thenComparing(Student::getName) → tie-breaker by alphabetical order.
- students.sort(comparator) applies ordering to list.
- Printed each student after sort.
Logic
- Inputs: list of 4 students.
- Output order:
1. Akshit (3.9)
2. Bob (3.7)
3. Alice (3.5)
4. Charlie (3.5)
- Flow:
1. GPA compared first.
2. For ties (Alice & Charlie, both 3.5), name ascending decides.
- Edge cases:
- Students with identical GPA and identical name considered equal by comparator.
- Complexity / performance: O(n log n).
- Concurrency / thread-safety: Local list, safe in demo.
- Error handling: Not applicable.
Real-life applications
- Student ranking systems where GPA is primary metric, names resolve ties.
- Leaderboards, employee sorting by salary then name.
- Demonstrates best practice for concise, readable comparator logic.
Notes
- Comparator.comparingDouble(Student::getGpa).reversed() avoids boxing cost of Double.
- The same comparator can be reused with Collections.sort(students, comparator).
- Compact and modern compared to manual if-else comparator logic.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent cee6a29 commit b26b112
File tree
1 file changed
+36
-0
lines changed- Section 25 Collections Frameworks/List Interface/ArrayList/Comparator/src
1 file changed
+36
-0
lines changedLines changed: 36 additions & 0 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
| 35 | + | |
| 36 | + | |
0 commit comments