JAVA基础知识-Map

JAVA基础知识-Map 相关知识。

遍历Map

方法一:

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
public class SlowMap {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("A", "01");
map.put("B", "02");
map.put("C", "03");
// 获取键的集合
Set<String> keySet = map.keySet();
// 利用set集合的迭代器
Iterator<String> iterator = keySet.iterator();
while(iterator.hasNext()) {
String key = iterator.next();
String value = map.get(key);
System.out.println("MAP INFO KEY:" + key + " VALUE:" + value);
}
}
}
```

> 方法二:

```java
public class QuickMap {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("A", "01");
map.put("B", "02");
map.put("C", "03");
// 通过entrySet()方法将map集合中的映射关系取出
Set<Map.Entry<String, String>> entry = map.entrySet();
// 利用关系集合entrySet的迭代器
Iterator<Map.Entry<String, String>> iterator = entry.iterator();
while(iterator.hasNext()) {
// 获取Map.Entry的关系对象me
Map.Entry<String, String> me = iterator.next();
// 通过关系对象获取key
String key = me.getKey();
// 通过关系对象获取value
String value = me.getValue();
System.out.println("Key :" + key + " value :" + value);
}
}
}

方法三:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class CollectionMap {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("A", "01");
map.put("B", "02");
map.put("C", "03");
// Collection集合存放Map的value值
Collection<String> collection = map.values();
// 遍历Collection
Iterator<String> it = collection.iterator();
// 只能遍历value值,不能遍历key值
while(it.hasNext()) {
Object value = it.next();
System.out.println(value);
}
}
}

最佳实践:

1
2
3
4
5
6
7
8
9
10
11
public class BestMap {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("A", "01");
map.put("B", "02");
map.put("C", "03");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
}
}
0%