How to iterate through a hashmap?

In Java, you can traverse a HashMap using the following method:

  1. return a set of keys
  2. iterate over each element
HashMap<String, Integer> hashMap = new HashMap<>();
// 添加键值对
hashMap.put("A", 1);
hashMap.put("B", 2);
hashMap.put("C", 3);

// 遍历
for (String key : hashMap.keySet()) {
    Integer value = hashMap.get(key);
    System.out.println(key + ": " + value);
}
  1. return a list of all the values in the dictionary
  2. go through each individual item
HashMap<String, Integer> hashMap = new HashMap<>();
// 添加键值对
hashMap.put("A", 1);
hashMap.put("B", 2);
hashMap.put("C", 3);

// 遍历
for (Integer value : hashMap.values()) {
    System.out.println(value);
}
  1. Returns a set view of the mappings contained in this map.
  2. iterate over each item
HashMap<String, Integer> hashMap = new 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();
    System.out.println(key + ": " + value);
}

These methods can be selected based on specific needs. Traversing by key can retrieve both the key and value, traversing by value can only retrieve the value, and using the Entry collection for traversal allows for the retrieval of both the key and value simultaneously.

bannerAds