java 循环遍历map
时间: 2024-01-27 19:15:17 浏览: 80
以下是Java中循环遍历Map的两种方式:
1. 使用for-each循环遍历Map的键值对:
```java
Map<Integer, String> map = new HashMap<>();
map.put(1, "apple");
map.put(2, "banana");
map.put(3, "orange");
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
```
2. 使用Iterator迭代器遍历Map的键值对:
```java
Map<Integer, String> map = new HashMap<>();
map.put(1, "apple");
map.put(2, "banana");
map.put(3, "orange");
Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, String> entry = iterator.next();
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
```
阅读全文