hashmap怎么遍历
遍历HashMap可以使用以下几种方法:
- 使用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
}
- 使用For-Each循环遍历:
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
}
- 遍历所有的Key:
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
}
- 遍历所有的Value:
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
}
请根据具体的需求选择合适的遍历方法。
版权声明
本文仅代表作者观点,不代表米安网络立场。
上一篇:租vps可以干什么 下一篇:Linux调整进程优先级renice命令使用指南
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。