Java - Iterating Through a HashMap

Java

·

1 min read

Since I began programming in Java, this is how I would iterate through a HashMap:

//Map of people's names and ages 
Map<String, Integer> map = new HashMap<>(); 
map.put("Bob", 24); 
map.put("Sally", 33); 
map.put("Klee", 12); 

for(String name : map.keySet(){
  System.out.println("Name: " + name + " Age: " + map.get(name)); 
}

In the code above, I use the keySet() method to obtain a set of keys in my HashMap, and then I iterate over it get the corresponding value using the get() method.

However, it has recently come to my attention that I can directly obtain a set of both the keys and values by using the entrySet() method.

for(Map.Entry<String,Integer> mapEntry : map.entrySet()){
    System.out.println("Name :" + mapEntry.getKey() + ", Age :" + mapEntry.getValue());
}