Commit e4cdbee
committed
feat(collections): implement list sorting in descending order using lambda comparator
What
- Added `Main.java` under `Package` to demonstrate sorting a `List<Integer>` in **descending order**.
- Showcased two equivalent approaches:
1. Using `Collections.sort(list, (a, b) -> b - a)`
2. Using `list.sort((a, b) -> b - a)` (preferred shorthand in Java 8+).
- Printed the sorted list to verify output.
Why
- Demonstrates practical use of **lambda expressions** as custom comparators.
- Highlights difference between traditional `Collections.sort()` and the newer `List.sort()` method.
- Reinforces how lambdas improve readability by avoiding verbose `Comparator` implementations.
Logic
1. A list of integers `[1,2,3,4,5,6,7]` is created.
2. To sort in descending order:
- The comparator `(a, b) -> b - a` is passed.
- If `b > a`, result > 0 → ensures larger numbers come before smaller ones.
3. Output confirms reversed order `[7,6,5,4,3,2,1]`.
4. Alternative approaches (commented out) illustrate flexibility:
- Using `Collections.sort()` with lambda.
- Using a separate comparator class (`MyClass`) if desired.
Key Takeaways
✔ `List.sort()` is the modern, concise way to sort collections (Java 8+).
✔ Lambdas simplify comparator definitions (`(a, b) -> b - a`).
✔ Sorting logic is customizable without creating boilerplate comparator classes.
✔ Comparator result convention: negative → first < second, positive → first > second.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent d441b81 commit e4cdbee
File tree
1 file changed
+29
-0
lines changed- Java 8 Crash Course/Lambda Expression/Comparator Using Lambda Expression/src/Package
1 file changed
+29
-0
lines changedLines changed: 29 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 | + | |
0 commit comments