-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHash map.TXT
More file actions
44 lines (37 loc) · 1.66 KB
/
Hash map.TXT
File metadata and controls
44 lines (37 loc) · 1.66 KB
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
import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
// Create a HashMap to store key-value pairs of String keys and Integer values
Map<String, Integer> hashMap = new HashMap<>();
// Adding elements to the HashMap
hashMap.put("John", 25);
hashMap.put("Alice", 30);
hashMap.put("Bob", 28);
// Accessing elements using their keys
System.out.println("Age of John: " + hashMap.get("John"));
System.out.println("Age of Alice: " + hashMap.get("Alice"));
// Iterating over the HashMap using a for-each loop
System.out.println("\nIterating over the HashMap:");
for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
System.out.println("Name: " + entry.getKey() + ", Age: " + entry.getValue());
}
// Checking if a key exists in the HashMap
String keyToCheck = "Alice";
if (hashMap.containsKey(keyToCheck)) {
System.out.println("\n" + keyToCheck + " is present in the HashMap.");
} else {
System.out.println("\n" + keyToCheck + " is not present in the HashMap.");
}
// Removing an element from the HashMap
String keyToRemove = "Bob";
if (hashMap.containsKey(keyToRemove)) {
hashMap.remove(keyToRemove);
System.out.println("\n" + keyToRemove + " is removed from the HashMap.");
} else {
System.out.println("\n" + keyToRemove + " is not present in the HashMap.");
}
// Size of the HashMap
System.out.println("\nSize of HashMap: " + hashMap.size());
}
}