java遍历map的几种方法
时间: 2023-11-28 14:46:06 浏览: 124
java遍历Map的几种方法分析
5星 · 资源好评率100%
以下是Java遍历Map对象的几种方法:
1. 使用for-each循环遍历Map对象
```java
Map<String, Integer> map = new HashMap<>();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println("Key: " + key + ", Value: " + value);
}
```
2. 使用Lambda表达式遍历Map对象
```java
Map<String, Integer> map = new HashMap<>();
map.forEach((key, value) -> System.out.println("Key: " + key + ", Value: " + value));
```
3. 使用Iterator迭代器遍历Map对象
```java
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();
System.out.println("Key: " + key + ", Value: " + value);
}
```
4. 使用Stream API遍历Map对象
```java
Map<String, Integer> map = new HashMap<>();
map.entrySet().stream().forEach(entry -> System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue()));
```
阅读全文