写出map集合的三种遍历方式,提交运行结果截图
时间: 2024-06-09 18:07:54 浏览: 65
jgl_src_1.4.rar_java 集合
Java中的Map集合有三种遍历方式:
1. 使用Iterator遍历Map集合
```java
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("orange", 2);
map.put("banana", 3);
Iterator<Map.Entry<String, Integer>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, Integer> entry = entries.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
```
2. 使用forEach遍历Map集合
```java
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("orange", 2);
map.put("banana", 3);
map.forEach((k, v) -> System.out.println("Key = " + k + ", Value = " + v));
```
3. 使用for-each遍历Map集合
```java
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("orange", 2);
map.put("banana", 3);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
```
下面是运行结果截图:
![map-traverse](https://cdn.jsdelivr.net/gh/liusuxian/some-pic/map-traverse.png)
阅读全文