HashMap的几种遍历方式案列
时间: 2023-07-24 15:06:56 浏览: 122
假设有一个HashMap<Integer, String> map,以下是几种遍历方式的示例代码:
1. 使用for-each循环遍历key
```
for(Integer key : map.keySet()) {
System.out.println("Key: " + key);
}
```
2. 使用for-each循环遍历value
```
for(String value : map.values()) {
System.out.println("Value: " + value);
}
```
3. 使用for-each循环遍历entry
```
for(Map.Entry<Integer, String> entry : map.entrySet()) {
Integer key = entry.getKey();
String value = entry.getValue();
System.out.println("Key: " + key + ", Value: " + value);
}
```
4. 使用Iterator遍历key
```
Iterator<Integer> iterator = map.keySet().iterator();
while(iterator.hasNext()) {
Integer key = iterator.next();
System.out.println("Key: " + key);
}
```
5. 使用Iterator遍历value
```
Iterator<String> iterator = map.values().iterator();
while(iterator.hasNext()) {
String value = iterator.next();
System.out.println("Value: " + value);
}
```
6. 使用Iterator遍历entry
```
Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();
while(iterator.hasNext()) {
Map.Entry<Integer, String> entry = iterator.next();
Integer key = entry.getKey();
String value = entry.getValue();
System.out.println("Key: " + key + ", Value: " + value);
}
```
阅读全文