HashMap Iteration in Java


Use keySet() to iterate over keys in a HashMap, and get(key) to retrieve the value associated with a key.

Source Code

HashMap capitalCities = new HashMap();
capitalCities.put("England", "London");
capitalCities.put("Germany", "Berlin");
for (String key : capitalCities.keySet()) {
    System.out.println("Key: " + key + ", Value: " + capitalCities.get(key));
}
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments