java – What is the best way to iterate over objects in a HashMap?

Question:

What's the best way to iterate over the objects in a HashMap in Java so that you have access to the key and value of each entry?

Answer:

I like to use the for loop because the code is leaner:

for (Map.Entry<String,Integer> pair : myHashMap.entrySet()) {
    System.out.println(pair.getKey());
    System.out.println(pair.getValue());
}
Scroll to Top