How do you iterate through a hashmap?
There are several ways to traverse a HashMap.
- Traverse using an Iterator:
HashMap<String, Integer> hashMap = new HashMap<>();
// 添加元素到HashMap
hashMap.put("A", 1);
hashMap.put("B", 2);
hashMap.put("C", 3);
Iterator<Map.Entry<String, Integer>> iterator = hashMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
String key = entry.getKey();
Integer value = entry.getValue();
// 在这里处理key和value
}
- Traverse using a For-Each loop:
HashMap<String, Integer> hashMap = new HashMap<>();
// 添加元素到HashMap
hashMap.put("A", 1);
hashMap.put("B", 2);
hashMap.put("C", 3);
for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
// 在这里处理key和value
}
- Iterate through all keys.
HashMap<String, Integer> hashMap = new HashMap<>();
// 添加元素到HashMap
hashMap.put("A", 1);
hashMap.put("B", 2);
hashMap.put("C", 3);
for (String key : hashMap.keySet()) {
Integer value = hashMap.get(key);
// 在这里处理key和value
}
- Iterate through all values.
HashMap<String, Integer> hashMap = new HashMap<>();
// 添加元素到HashMap
hashMap.put("A", 1);
hashMap.put("B", 2);
hashMap.put("C", 3);
for (Integer value : hashMap.values()) {
// 在这里处理value
}
Please choose the appropriate traversal method based on specific needs.