写几种map集合的遍历
时间: 2023-11-08 13:13:43 浏览: 96
map集合遍历的五种方法
可以参考以下的几种遍历方式:
1. 使用Entry遍历方法:
```
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("key: " + entry.getKey() + ", value: " + entry.getValue());
}
```
2. 使用迭代器遍历方法:
```
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
System.out.println("key: " + entry.getKey() + ", value: " + entry.getValue());
}
```
3. 遍历键集合:
```
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
for (String key : map.keySet()) {
System.out.println("key: " + key + ", value: " + map.get(key));
}
```
4. 遍历值集合:
```
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
for (String value : map.values()) {
System.out.println("value: " + value);
}
```
阅读全文