遍历map集合的集中方式
时间: 2023-11-08 22:13:54 浏览: 45
1. 使用 for-each 循环遍历 Map 的键或值:
```java
Map<String, Integer> map = new HashMap<>();
for (String key : map.keySet()) {
Integer value = map.get(key);
System.out.println(key + " = " + value);
}
for (Integer value : map.values()) {
System.out.println(value);
}
```
2. 使用迭代器遍历 Map 的键或值:
```java
Iterator<String> keyIterator = map.keySet().iterator();
while (keyIterator.hasNext()) {
String key = keyIterator.next();
Integer value = map.get(key);
System.out.println(key + " = " + value);
}
Iterator<Integer> valueIterator = map.values().iterator();
while (valueIterator.hasNext()) {
Integer value = valueIterator.next();
System.out.println(value);
}
```
3. 使用 Java 8 中的 Stream API 遍历 Map:
```java
map.forEach((key, value) -> System.out.println(key + " = " + value));
map.keySet().stream().forEach(key -> {
Integer value = map.get(key);
System.out.println(key + " = " + value);
});
map.values().stream().forEach(value -> System.out.println(value));
```
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)