Loop Through a HashMap
Traverse through the entries of a HashMap utilizing a for-each loop.
Note: Utilize the keySet() method for keys only, and the values() method for values only.
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 ));
}
|