Iterate through a HashMap

There are several ways to iterate through a HashMap in Java:

  1. Using the for-each loop:
HashMap<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);

for (Map.Entry<String, Integer> entry : map.entrySet()) {
    String key = entry.getKey();
    Integer value = entry.getValue();
    System.out.println(key + " : " + value);
}
  1. Using the Iterator:
HashMap<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);

Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
    Map.Entry<String, Integer> entry = iterator.next();
    String key = entry.getKey();
    Integer value = entry.getValue();
    System.out.println(key + " : " + value);
}
  1. Using the for-each method of the map.keySet():
HashMap<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);

for (String key : map.keySet()) {
    Integer value = map.get(key);
    System.out.println(key + " : " + value);
}
  1. Using the for-each method of the map.values():
HashMap<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);

for (Integer value : map.values()) {
    System.out.println(value);
}

Note that the order in which the elements are iterated is not guaranteed to be the same as the order in which they were added to the HashMap. If you need to iterate through the elements in the order they were added, you can use a LinkedHashMap instead.