java 遍历 map
时间: 2023-09-09 15:10:39 浏览: 129
在Java中,可以使用不同的方法来遍历Map。下面是几种常用的方法:
1. 使用Map的keySet()方法遍历键:
```java
Map<String, Integer> map = new HashMap<>();
// 添加键值对到map中
// ...
for (String key : map.keySet()) {
Integer value = map.get(key);
// 处理键值对
}
```
2. 使用Map的values()方法遍历值:
```java
Map<String, Integer> map = new HashMap<>();
// 添加键值对到map中
// ...
for (Integer value : map.values()) {
// 处理值
}
```
3. 使用Map的entrySet()方法遍历键值对:
```java
Map<String, Integer> map = new HashMap<>();
// 添加键值对到map中
// ...
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
// 处理键值对
}
```
这些方法都可以用来遍历Map,并根据需要处理键、值或键值对。根据具体情况选择最适合的方法进行遍历。
阅读全文
相关推荐




