Commit dd5ef5e
committed
feat(collections): add TreeMap demo with natural vs custom key ordering
What
- Added `Main2.java` in `Package2` to demonstrate `TreeMap` ordering behavior.
- Showed:
1. Natural ordering (ascending by keys, default behavior).
2. Custom ordering (descending by keys using lambda comparator).
- Printed maps to compare key ordering in both cases.
Why
- `TreeMap` is a sorted map that orders entries based on key ordering or a provided comparator.
- Demonstrating both natural and custom comparators clarifies how map iteration order is controlled.
- Useful in real-world scenarios where ordered dictionaries are required (e.g., leaderboards, priority mappings).
Logic
1. Created a `TreeMap<Integer, String>` with no comparator:
- Defaults to **natural ascending key order**.
- Input: `{22=Z, 1=f, 13=y}`
- Stored/iterated as: `{1=f, 13=y, 22=Z}`.
2. Created a second `TreeMap<Integer, String>` with custom comparator `(a, b) -> b - a`:
- Orders keys in **descending order**.
- Input: `{22=z, 1=f, 13=y}`
- Stored/iterated as: `{22=z, 13=y, 1=f}`.
3. Printed both results to highlight ordering difference.
Key Takeaways
✔ `TreeMap` maintains sorted keys by default (ascending order).
✔ Supplying a comparator changes the key ordering policy.
✔ `(a, b) -> b - a` reverses natural order into descending.
✔ Different comparators → different logical "views" of the same data.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent e59bec3 commit dd5ef5e
File tree
1 file changed
+22
-0
lines changed- Java 8 Crash Course/Lambda Expression/Comparator Using Lambda Expression/src/Package2
1 file changed
+22
-0
lines changedLines changed: 22 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 | + | |
0 commit comments