Commit fc5fe72
committed
feat(LambdaExpressionDemo): add demo of sorting collections using lambdas
What
- Added LambdaExpressionDemo class.
- Created a List<Integer> with values [2, 3, 1].
- Sorted integers in descending order using a lambda comparator (b - a).
- Created a List<String> with values ["banana", "apple", "date"].
- Sorted strings by length using a lambda comparator (a.length() - b.length()).
- Printed sorted results.
Why
- Demonstrates how to use lambda expressions to define custom comparators inline.
- Replaces verbose anonymous classes with concise, readable lambdas.
- Shows sorting of both numeric and string data with different criteria.
How
- list.sort((a, b) -> b - a):
- Subtracts a from b to achieve descending order.
- words.sort((a, b) -> a.length() - b.length()):
- Compares based on string length, resulting in ascending order by length.
- Print the lists after sorting to verify order.
Logic
- Inputs:
- list = [2, 3, 1].
- words = ["banana", "apple", "date"].
- Outputs:
- Integers sorted descending → [3, 2, 1].
- Strings sorted by length ascending → ["date", "apple", "banana"].
- Flow:
1. Populate lists.
2. Apply sort() with lambdas.
3. Print sorted collections.
- Edge cases:
- If comparator returns 0, elements considered equal (order may remain stable).
- If lists are empty, sort() is a no-op.
- Complexity: O(n log n) sorting.
- Concurrency: Not thread-safe while sorting shared mutable lists.
- Error handling: Not needed here.
Real-life applications
- Sorting employees by salary, then by name.
- Sorting files by size or timestamp.
- Sorting strings by custom metrics (length, frequency of characters, etc.).
- Inline comparators reduce boilerplate in such tasks.
Notes
- Lambdas improve readability compared to explicit Comparator classes.
- For clarity, use Comparator.comparing(...) when criteria are more complex.
- Arithmetic-based comparator (b - a) works for small integers but may overflow; safer is Integer.compare(b, a).
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent d57d6c3 commit fc5fe72
File tree
1 file changed
+2
-4
lines changed- Section 25 Collections Frameworks/List Interface/ArrayList/Lamda Expression/src
1 file changed
+2
-4
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
3 | 1 | | |
4 | 2 | | |
5 | 3 | | |
6 | 4 | | |
7 | | - | |
| 5 | + | |
8 | 6 | | |
9 | 7 | | |
10 | 8 | | |
| |||
18 | 16 | | |
19 | 17 | | |
20 | 18 | | |
21 | | - | |
| 19 | + | |
0 commit comments