java中map遍历代码实现
时间: 2023-11-20 21:56:43 浏览: 92
Java中Map的遍历可以使用以下几种方式实现:
1. 使用for-each循环遍历entrySet
```java
Map<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
```
2. 使用for-each循环遍历keySet
```java
Map<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
for (String key : map.keySet()) {
System.out.println("Key = " + key + ", Value = " + map.get(key));
}
```
3. 使用Iterator遍历entrySet
```java
Map<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
```
4. 使用Lambda表达式遍历entrySet
```java
Map<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
map.forEach((key, value) -> System.out.println("Key = " + key + ", Value = " + value));
```
阅读全文