-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMapDemo.java
More file actions
46 lines (42 loc) · 1.67 KB
/
MapDemo.java
File metadata and controls
46 lines (42 loc) · 1.67 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
45
46
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
public class MapDemo {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("1", "Value1");
map.put("2", "Value2");
map.put("3", "Value3");
map.put(null, "11");
//第一种:普遍使用,二次取值
System.out.println("通过Map.keySet遍历key和value:");
for (String key :
map.keySet()) {
System.out.println(key);
}
for (String value :
map.values()) {
System.out.println(value);
}
//第二种
System.out.println("通过Map.entrySet使用iterator遍历key和value:");
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
System.out.println("key=" + entry.getKey() + " and value=" + entry.getValue());
}
//第三种:推荐,尤其是容量大时
System.out.println("通过Map.entrySet遍历key和value");
for (Map.Entry<String, String> entry : map.entrySet()
) {
System.out.println("key=" + entry.getKey() + " and value=" + entry.getValue());
}
//第四种:尤其推荐
map.forEach((k, v) -> System.out.println("Key=" + k + ",Value=" + v));
Vector vector = new Vector();
vector.add("11");
// Map<String,Integer> stringIntegerMap=new ConcurrentHashMap<>();
// stringIntegerMap.put(null,11);
HashSet hashSet = new HashSet();
hashSet.add(11);
}
}