-
Notifications
You must be signed in to change notification settings - Fork 164
/
Copy pathHashMapExample.java
43 lines (33 loc) · 1.07 KB
/
HashMapExample.java
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
// Import the HashMap class
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
// Create a HashMap object called map
HashMap<String, String> map = new HashMap<String, String>();
// Add keys and values (Country, City)
map.put("England", "London");
map.put("Germany", "Berlin");
map.put("Norway", "Oslo");
map.put("USA", "Washington DC");
// Prints key value pairs
System.out.println(map);
// To access value
map.get("England");
// To remove an item
map.remove("England");
// To find out the number of items
map.size();
// Looping through the items in HashMap
// and printing the keys
for (String i : map.keySet()) {
System.out.println(i);
}
// Looping through the items in HashMap
// and printing the values
for (String i : map.values()) {
System.out.println(i);
}
// To remove all items
map.clear();
}
}