Commit 5b7a095
committed
feat(LinkedListDemo1): add examples of sorting and removing elements in LinkedList
What
- Created `LinkedListDemo1` to demonstrate:
- Sorting a `LinkedList<Integer>` using `sort(null)` (natural ordering).
- Removing even numbers with `removeIf(predicate)`.
- Removing all elements in one list that exist in another using `removeAll()`.
- Added examples with both integers and strings.
Why
- Show practical `LinkedList` operations beyond basic add/get:
- Sorting in-place with natural order.
- Using `removeIf` for conditional removal (functional style).
- Using `removeAll` to bulk-remove a set of elements.
- Reinforces that `LinkedList` supports all `List` interface operations, not just queue-like ones.
How
- Built an integer `LinkedList` with mixed values.
- Called `linkedList.sort(null)` to apply natural ascending sort.
- Used `linkedList.removeIf(x -> x % 2 == 0)` to filter odd numbers.
- Created two string `LinkedList`s: `animals` and `animalsToRemove`.
- Called `animals.removeAll(animalsToRemove)` to delete specific elements.
- Printed intermediate results after each operation.
Logic
1. Insert values `[1,2,3,4,5,7,6,8,9,10,44,46,70]`.
2. Sort → `[1,2,3,4,5,6,7,8,9,10,44,46,70]`.
3. Remove evens → `[1,3,5,7,9]`.
4. On `animals`: start `[Cat, Dog, Elephant, lion]`.
5. Remove all `["Dog","lion"]` → `[Cat, Elephant]`.
Complexity
- `sort()` → O(n log n), uses TimSort.
- `removeIf()` → O(n), traverses once.
- `removeAll()` → O(n*m) worst case (n = size of list, m = size of removal list), though optimized internally via hashing for certain collections.
- LinkedList operations like add/remove at ends are O(1); traversal-based ones (like sort or indexed access) are slower (O(n)).
Applications
- Filtering collections by condition (removeIf).
- Bulk removal (removeAll) for lists that need to sync with others.
- Sorting data stored in LinkedList, though usually ArrayList is more efficient for sorting and random access.
Notes
- `LinkedList` implements `List`, `Deque`, `Queue`.
- `sort(null)` means natural ordering; can pass a `Comparator` for custom order.
- `removeIf` is a Java 8 feature; more concise than manual iteration.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent ddea815 commit 5b7a095
File tree
1 file changed
+6
-8
lines changed- Section 25 Collections Frameworks/List Interface/LinkedList/src
1 file changed
+6
-8
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 | | |
| |||
20 | 18 | | |
21 | 19 | | |
22 | 20 | | |
23 | | - | |
| 21 | + | |
24 | 22 | | |
25 | 23 | | |
26 | | - | |
27 | | - | |
28 | | - | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
29 | 27 | | |
30 | 28 | | |
31 | 29 | | |
| |||
34 | 32 | | |
35 | 33 | | |
36 | 34 | | |
37 | | - | |
| 35 | + | |
0 commit comments