遍历HashMap可以使用以下几种方法:
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
}
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
}
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
}
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
}
请根据具体的需求选择合适的遍历方法。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:hashmap如何遍历