J.Nemo

Stay Hungry, Stay Foolish

Map集合的遍历方法

Map遍历的方法总结下来,大概分为四种,以下是具体的展示。

1.通过Map.KeySet遍历key和value

1
2
3
4
5
6
7
8
9
Map<String, String> map = new HashMap<>();
map.put("甘肃", "兰州");
map.put("陕西", "西安");
map.put("新疆", "乌鲁木齐");
map.put("青海", "西宁");
map.put("宁夏", "银川");
for (String key : map.keySet()) {
System.out.println("key= " + key + " and value= " + map.get(key));
}

2.通过Map.entrySet遍历key和value

1
2
3
4
5
6
7
8
9
10
11
Map<String, String> map = new HashMap<>();
map.put("甘肃", "兰州");
map.put("陕西", "西安");
map.put("新疆", "乌鲁木齐");
map.put("青海", "西宁");
map.put("宁夏", "银川");
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
System.out.println("key= " + key + " and value= " + value);
}

3.通过Map.entrySet使用iterator遍历key和value

1
2
3
4
5
6
7
8
9
10
11
12
13
Map<String, String> map = new HashMap<>();
map.put("甘肃", "兰州");
map.put("陕西", "西安");
map.put("新疆", "乌鲁木齐");
map.put("青海", "西宁");
map.put("宁夏", "银川");
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println("key= " + key + " and value= " + value);
}

4.通过Map.values()遍历value,无法遍历key

1
2
3
4
5
6
7
8
9
Map<String, String> map = new HashMap<>();
map.put("甘肃", "兰州");
map.put("陕西", "西安");
map.put("新疆", "乌鲁木齐");
map.put("青海", "西宁");
map.put("宁夏", "银川");
for (String value : map.values()) {
System.out.print("value= " + value);
}