ハッシュマップをどのように走査しますか?

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. すべてのキーを巡回する:
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. すべての値を選択する:
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
}

具体の要求に基づいて、適切なトラバーサル方法を選択してください。

bannerAds