forked from AndrewProgramming/JavaTutorialCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMapDemo.java
More file actions
38 lines (28 loc) · 1.1 KB
/
MapDemo.java
File metadata and controls
38 lines (28 loc) · 1.1 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
package collection;
import java.util.HashMap;
import java.util.Map;
public class MapDemo {
public static void main(String[] args) {
//create a new map
Map<String, String> hashMap = new HashMap<>();
//add three elements
hashMap.put("Andrew", "Deng");
hashMap.put("Kobe", "Bryant");
hashMap.put("Leborn", "James");
System.out.println(hashMap);
//remove an element
hashMap.remove("Andrew");
System.out.println(hashMap);
//check if map is empty
System.out.println("hashmap is empty? " + hashMap.isEmpty());
//check if map contains key Kobe
System.out.println("contains key Kobe? " + hashMap.containsKey("Kobe"));
//check if map contains value Bryant
System.out.println("contains value Bryant? " + hashMap.containsValue("Bryant"));
//traversing the map
System.out.println("------start traversing the map------");
for (Map.Entry<String, String> entry : hashMap.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
}