Commit 62c3e10
committed
feat(collections): demonstrate sorting custom objects with lambda-based Comparator
What
- Added `Main.java` in `Package3` to illustrate sorting of custom objects (`Student`) using `Collections.sort` with a comparator.
- Defined `Student` as a static inner class with fields:
- `id` (Integer)
- `name` (String)
- Created a list of students and applied a **custom comparator** to sort them in descending order of `id`.
- Overrode `toString()` in `Student` for readable output (e.g., `33: Donald`).
Why
- By default, Java’s `Collections.sort()` relies on natural ordering (like integers, strings).
- For custom objects, we must explicitly define sorting rules via:
- Implementing `Comparable<T>` (natural order), or
- Providing a `Comparator<T>` (custom order).
- This example shows how to sort domain-specific objects (like students) with a comparator inline via lambda.
Logic
1. Constructed 3 students with different IDs and names.
2. Added them to a `List<Student>`.
3. Used `Collections.sort(li, (a, b) -> b.id - a.id)`:
- Comparator subtracts `id` values → sorts descending by ID.
- Demonstrates custom ordering beyond natural sorting.
4. Printed the sorted list, relying on overridden `toString()` for formatted display.
Key Takeaways
✔ Custom objects don’t have inherent ordering — you must define it.
✔ Comparator lambdas provide concise, inline sorting logic.
✔ `(a, b) -> b.id - a.id` → descending sort by ID.
✔ For ascending order: `(a, b) -> a.id - b.id`.
✔ `toString()` improves debugging/logging by showing meaningful output.
✔ Collections framework integrates seamlessly with lambdas introduced in Java 8.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent dd5ef5e commit 62c3e10
File tree
1 file changed
+39
-0
lines changed- Java 8 Crash Course/Lambda Expression/Comparator Using Lambda Expression/src/Package3
1 file changed
+39
-0
lines changedLines changed: 39 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 | + | |
| 37 | + | |
| 38 | + | |
| 39 | + | |
0 commit comments