Java 遍历HashMap例子
时间: 2024-02-09 09:04:35 浏览: 84
以下是Java遍历HashMap的两个例子:
1.使用for-each循环遍历HashMap
```java
HashMap<String, Integer> myHashMap = new HashMap<>();
myHashMap.put("1", 1);
myHashMap.put("2", 2);
for (Map.Entry<String, Integer> entry : myHashMap.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key + " : " + value);
}
```
2.使用Iterator遍历HashMap
```java
HashMap<String, Integer> myHashMap = new HashMap<>();
myHashMap.put("1", 1);
myHashMap.put("2", 2);
Iterator<Map.Entry<String, Integer>> iterator = myHashMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key + " : " + value);
}
```
阅读全文