Skip to content

Commit 29d1968

Browse files
committed
feat: Demonstrate key, value, and entry iteration using Java HashMap
🧠 Logic: - Created a `HashMap<String, Integer>` to store student names and their ages. - Populated the map with three entries: Alice, Bob, and Charlie. - Used enhanced for-loops to: - Print all keys using `keySet()`. - Print all values using `values()`. - Print key-value pairs using `entrySet()` with `Map.Entry`. - Effectively illustrates how Java maps (like dictionaries) can be traversed in multiple ways. Signed-off-by: Somesh diwan <[email protected]>
1 parent 31cf982 commit 29d1968

File tree

1 file changed

+4
-10
lines changed

1 file changed

+4
-10
lines changed

Section8LoopAB/Loop 2.O/src/ForLoopDictionaries.java

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,33 +4,27 @@
44
import java.util.Map;
55

66
public class ForLoopDictionaries {
7-
public static void main(String[] args)
8-
{
7+
public static void main(String[] args) {
98
Map<String, Integer> student = new HashMap<>();
109
student.put("Alice", 20);
1110
student.put("Bob", 22);
1211
student.put("Charlie", 19);
1312

1413
// Iterating through keys
15-
1614
System.out.println("Keys:");
17-
for (String key : student.keySet())
18-
{
15+
for (String key : student.keySet()) {
1916
System.out.println(key);
2017
}
2118

2219
// Iterating through values
2320
System.out.println("\nValues:");
24-
for (int value : student.values())
25-
{
21+
for (int value : student.values()) {
2622
System.out.println(value);
2723
}
2824

2925
// Iterating through key-value pairs
30-
3126
System.out.println("\nKey-Value Pairs:");
32-
for (Map.Entry<String, Integer> entry : student.entrySet())
33-
{
27+
for (Map.Entry<String, Integer> entry : student.entrySet()) {
3428
System.out.println(entry.getKey() + ": " + entry.getValue());
3529
}
3630
}

0 commit comments

Comments
 (0)