Java如何遍历HashMap?
时间: 2023-05-26 15:05:28 浏览: 181
怎样遍历一个HashMap?
4星 · 用户满意度95%
Java可以使用迭代器(Iterator)或者增强for循环(for-each loop)来遍历HashMap。
使用迭代器遍历HashMap:
```java
HashMap<String, String> map = new HashMap<>();
map.put("1", "one");
map.put("2", "two");
map.put("3", "three");
Iterator<Map.Entry<String,String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String,String> entry = iterator.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
```
使用增强for循环遍历HashMap:
```java
HashMap<String, String> map = new HashMap<>();
map.put("1", "one");
map.put("2", "two");
map.put("3", "three");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
```
两种方法的输出结果都是:
```
Key = 1, Value = one
Key = 2, Value = two
Key = 3, Value = three
```
阅读全文