HashMap: Iteration

Let's see how we can iterate the elements of a HashMap.

Iterating a HashMap is a bit challenging compared to a List or a Set as it contains pairs of elements. In a map, each key-value pair is called Entry. The entrySet() method returns the Set view of the mapped elements. We can iterate over this Set using any of the below approaches.

Iterating using a for loop

We can easily iterate the EntrySet returned by the entrySet() method using an enhanced for loop. The Entry class contains two methods: getKey() and getValue(), which can be used to get the key and value respectively.

Get hands-on with 1400+ tech skills courses.