Commit 5544a0f
committed
feat(ListDemo2): add demo of custom sorting with lambdas
What
- Added ListDemo2 class.
- Created List<String> with values ["banana","apple","date"].
- Sorted strings by length in descending order using lambda comparator (b.length() - a.length()).
- Created List<Integer> with values [2,1,3].
- Sorted integers in descending natural order using lambda comparator (b - a).
- Printed sorted results.
Why
- Demonstrates custom sorting logic using lambda expressions.
- Shows how to sort strings by length instead of natural alphabetical order.
- Shows how to sort integers descending without using Comparator.reverseOrder().
- Useful example of how lambdas simplify comparator creation.
How
- words = ["banana","apple","date"].
- words.sort((a,b) -> b.length() - a.length()) → ["banana","apple","date"] (lengths: 6,5,4).
- ints = [2,1,3].
- ints.sort((a,b) -> b - a) → [3,2,1].
- Printed both results.
Logic
- Inputs: strings and integers.
- Outputs:
- Strings sorted by descending length.
- Integers sorted descending.
- Flow:
1. Initialize string and integer lists.
2. Apply sort() with lambda comparator.
3. Print final results.
- Edge cases:
- Comparator using subtraction can overflow for large integers; safer to use Integer.compare(b,a).
- Stable sort: equal lengths keep original order.
- Complexity: O(n log n) sorting.
- Concurrency: not thread-safe if lists modified concurrently.
Real-life applications
- Sorting strings by length for UI display (e.g., longest words first).
- Sorting integers descending for leaderboards, rankings, or high-score lists.
- Custom comparator lambdas eliminate boilerplate comparator classes.
Notes
- words.sort(null) would sort alphabetically; custom comparator overrides natural order.
- Comparator.comparingInt(String::length).reversed() is a more readable alternative to b.length() - a.length().
- For integers, Comparator.reverseOrder() achieves the same descending effect.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent a06a4af commit 5544a0f
File tree
1 file changed
+25
-0
lines changed- Section 25 Collections Frameworks/List Interface/ArrayList/src
1 file changed
+25
-0
lines changedLines changed: 25 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 | + | |
0 commit comments