How to Iterate Through a HashMap in Java

The HashMap class is a convenient way to store key-value pairs in Java without having to create a custom class to do this. It’s nice that you can iterate through it using the keys.


java.util.HashMap map = new java.util.HashMap();
map.put("ABC", "123");
map.put("DEF", "456");

for (String key : map.keySet())
  System.out.println(key + " - " + map.get(key));

This results in:

ABC – 123
DEF – 456

Leave a Reply