Commit 4dabc3d
committed
feat(ListDemo): add demo of sorting lists with Collections.sort and List.sort
What
- Added ListDemo class.
- Created a List<Integer> with values [1,3,2].
- Demonstrated sorting with list.sort(null), which uses natural ordering (ascending).
- Created a List<String> with values ["banana","apple","date"].
- Sorted words with list.sort(null) (alphabetical order).
- Printed sorted results.
Why
- Shows two equivalent ways of sorting lists:
- Collections.sort(list).
- list.sort(null) (preferred since Java 8).
- Demonstrates natural ordering:
- For integers → ascending numeric order.
- For strings → lexicographical order.
How
- list = [1,3,2].
- list.sort(null) → [1,2,3].
- words = ["banana","apple","date"].
- words.sort(null) → ["apple","banana","date"].
- Printed both lists.
Logic
- Inputs: integer and string lists.
- Outputs:
- Sorted integers ascending.
- Sorted strings alphabetically.
- Flow:
1. Initialize lists.
2. Sort integers with list.sort(null).
3. Sort strings with list.sort(null).
4. Print results.
- Edge cases:
- Passing null to sort() means use natural ordering.
- For custom order, pass Comparator (e.g., Comparator.reverseOrder()).
- Complexity: O(n log n) sort.
- Concurrency: Not thread-safe if list is modified concurrently.
Real-life applications
- Sorting numerical or textual data for reporting, searching, or UI display.
- Using natural ordering without writing explicit comparators.
- Switching between natural and custom order by replacing null with Comparator.
Notes
- Collections.sort(list) and list.sort(null) are interchangeable; list.sort is more modern and direct.
- Natural ordering is defined by Comparable implementation of list elements.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 3acfa5e commit 4dabc3d
File tree
1 file changed
+3
-5
lines changed- Section 25 Collections Frameworks/List Interface/ArrayList/src
1 file changed
+3
-5
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 | | |
| |||
11 | 9 | | |
12 | 10 | | |
13 | 11 | | |
14 | | - | |
| 12 | + | |
15 | 13 | | |
16 | 14 | | |
17 | 15 | | |
18 | 16 | | |
19 | 17 | | |
20 | 18 | | |
21 | 19 | | |
22 | | - | |
| 20 | + | |
0 commit comments