Commit 1acc585
committed
feat(SortedMapDemo): demonstrate TreeMap with custom reverse-order comparator
What
- Added `SortedMapDemo` class using a `TreeMap` with a custom comparator for descending key order.
- Showcased core `SortedMap` operations:
- `put()` to insert entries.
- `get()`, `containsKey()`, and `containsValue()`.
- Views: `firstKey()`, `lastKey()`, `headMap()`, and `tailMap()` (commented for demo flexibility).
Why
- To illustrate how `SortedMap` works in Java and how `TreeMap` maintains key ordering.
- Useful for scenarios requiring ordered key-value mappings with custom sorting logic.
How
- Created a `TreeMap<Integer, String>` with comparator `(a, b) -> b - a` to enforce descending order of keys.
- Inserted sample student scores (`99`, `91`, `78`, `77`) mapped to names.
- Highlighted the effect of the comparator on order and how to query ranges.
Logic
- Keys are sorted in reverse order due to comparator.
- Insert sequence: 91, 99, 78, 77.
- Resulting order: 99 → 91 → 78 → 77.
- `firstKey()` → 99 (highest).
- `lastKey()` → 77 (lowest).
- `headMap(91)` → keys greater than 91 in descending order → [99].
- `tailMap(91)` → keys ≤ 91 in descending order → [91, 78, 77].
Real-life applications
- Maintaining leaderboards (highest score first).
- Stock price tickers (most recent/highest values prioritized).
- Priority-based mappings where descending order of keys is important.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 8796101 commit 1acc585
File tree
1 file changed
+45
-0
lines changed- Section 25 Collections Frameworks/Map Interface/Sorted Map/src
1 file changed
+45
-0
lines changedLines changed: 45 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 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
| 35 | + | |
| 36 | + | |
| 37 | + | |
| 38 | + | |
| 39 | + | |
| 40 | + | |
| 41 | + | |
| 42 | + | |
| 43 | + | |
| 44 | + | |
| 45 | + | |
0 commit comments