java中遍历map的方式
时间: 2024-05-10 22:12:30 浏览: 101
Java中遍历Map的方式有以下几种:
1. 使用for-each循环遍历Map的entrySet()
```
Map<String, Integer> map = new HashMap<>();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
// do something with key and value
}
```
2. 使用for-each循环遍历Map的keySet()
```
Map<String, Integer> map = new HashMap<>();
for (String key : map.keySet()) {
Integer value = map.get(key);
// do something with key and value
}
```
3. 使用迭代器遍历Map的entrySet()
```
Map<String, Integer> map = new HashMap<>();
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
String key = entry.getKey();
Integer value = entry.getValue();
// do something with key and value
}
```
4. 使用Java8的Lambda表达式遍历Map的entrySet()
```
Map<String, Integer> map = new HashMap<>();
map.forEach((key, value) -> {
// do something with key and value
});
```
阅读全文