hashmap的遍历
时间: 2023-10-19 11:27:57 浏览: 97
HashMap的遍历可以通过以下几种方式实现:
1. 使用Iterator遍历:
```java
HashMap<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "Apple");
hashMap.put(2, "Banana");
hashMap.put(3, "Cherry");
Iterator<Map.Entry<Integer, String>> iterator = hashMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, String> entry = iterator.next();
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
```
2. 使用forEach循环遍历:
```java
HashMap<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "Apple");
hashMap.put(2, "Banana");
hashMap.put(3, "Cherry");
hashMap.forEach((key, value) -> System.out.println("Key: " + key + ", Value: " + value));
```
3. 遍历键集合或值集合:
```java
HashMap<Integer, String> hashMap = new HashMap<>();
hashMap.put(1, "Apple");
hashMap.put(2, "Banana");
hashMap.put(3, "Cherry");
// 遍历键集合
for (Integer key : hashMap.keySet()) {
System.out.println("Key: " + key + ", Value: " + hashMap.get(key));
}
// 遍历值集合
for (String value : hashMap.values()) {
System.out.println("Value: " + value);
}
```
以上是常见的HashMap遍历方式,根据具体需求选择适合的方式进行遍历。
阅读全文