Commit 9dda328
committed
feat(HashMapDemo3): add HashMap entrySet iteration and formatted printing demo
What
- Implemented `HashMapDemo3` to show how to retrieve entries from a `HashMap` using `entrySet()`
and iterate over them with formatted output.
- Added logic to print both the original map and processed key–value pairs.
Why
- Demonstrates a more structured way of accessing `HashMap` contents (key + value together).
- Highlights the fact that `HashMap` does not maintain insertion or sorted order.
- Provides an example of formatting values (e.g., uppercase transformation) without modifying the original map.
How
1. Created a `HashMap<Integer, String>` and inserted sample entries (`Jack`, `Smith`, `Shubham`, `John`).
2. Printed the original map directly.
3. Retrieved entries via `map.entrySet()`.
4. Iterated over each entry:
- Printed key and value with formatted width using `printf`.
- Printed the uppercase version of the value (demonstrating transformation without changing the map).
5. Printed the final map again to show contents remain unchanged.
Notes on ordering
- `HashMap` **does not guarantee iteration order**.
- The printed order depends on hash distribution and internal bucket structure.
- With a small number of elements, output may look "sorted" by coincidence, but this is unreliable.
- For predictable ordering:
- Use `LinkedHashMap` → preserves insertion order.
- Use `TreeMap` → sorts by key.
Real-life application
- Iterating key–value mappings for reporting, logging, or transforming data (like uppercase conversion).
- Useful in scenarios like processing user IDs → names, product IDs → details, etc.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 377d2fd commit 9dda328
File tree
1 file changed
+48
-0
lines changed- Section 25 Collections Frameworks/Map Interface/HashMap/src
1 file changed
+48
-0
lines changedLines changed: 48 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 | + | |
| 46 | + | |
| 47 | + | |
| 48 | + | |
0 commit comments