Iterate over a HashMap

Iterate elements in a HashMap using different methods in Java.

Iterate using entrySet()

entrySet() returns a set of key-value pairs() contained in the map. It is the most efficient way to iterate over a HashMap.

1
2
3
4
5
6
7
8
9
HashMap<String,String> map = new HashMap<>();
map.put("Key1", "Value1");
map.put("Key2", "Value2");
map.put("Key3", "Value3");
map.put("Key4", "Value4");

map.entrySet().forEach(entry -> {
System.out.println(entry.getKey() + " " + entry.getValue());
});

Iterate using forEach()

1
2
3
4
5
6
7
8
9
HashMap<String,String> map = new HashMap<>();
map.put("Key1", "Value1");
map.put("Key2", "Value2");
map.put("Key3", "Value3");
map.put("Key4", "Value4");

map.forEach((key, value) -> {
System.out.println(key + " " + value);
});