溫馨提示×

hashmap怎么遍歷

小億
91
2024-01-11 07:42:03
欄目: 編程語言

遍歷HashMap可以使用以下幾種方法:

  1. 使用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
}
  1. 使用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
}
  1. 遍歷所有的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
}
  1. 遍歷所有的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
}

請根據具體的需求選擇合適的遍歷方法。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女