Java How To Loop Through a HashMap

Loop Through a HashMap

Loop through the items of a HashMap with a for-each loop.

Note: Use the keySet() method if you only want the keys, and use the values() method if you only want the values:

Example

// Print keys
for (String i : capitalCities.keySet()) {
  System.out.println(i);
}

 

Example

// Print values
for (String i : capitalCities.values()) {
  System.out.println(i);
}

 

Example

// Print keys and values
for (String i : capitalCities.keySet()) {
  System.out.println("key: " + i + " value: " + capitalCities.get(i));
}