In this article we are going to see how to iterate java map in different approaches with simple examples, we will go through different ways of iterating map in java before and after Java 8. And also we are going to see usage of keySet(), values(), entrySet(), forEach() methods of Java Map interface. These methods are common for any Map implementation classes.

  1. Iterate Java Map

Below are the most commonly used approaches  to iterate Java Map.

  1. Iterate map using collections Iterator.
  2. Iterate Java Map using keySet() through for-each loop.
  3. Iterate Map using entrySet() through for-each loop.
  4. Iterate Map using java 8 forEach() method, functional style.
  5. Iterate Map using java 8 Stream forEach() method.

2. Approaches before Java 8

2.1. Using collections Iterator

We can use Iterator to get objects one by one from any collection object. We can apply Iterator concept for any collection object and it is a universal cursor. Below example illustrates  how to iterate a Map using Iterator and also demonstrates keySet(), values() methods of map.

Copy to Clipboard

Output

Copy to Clipboard

2.2. Iterate Java Map using keySet() through for-each loop

Copy to Clipboard

Output

Copy to Clipboard

2.3. Iterate Java Map using entrySet() through for-each loop

What is Map Entry?:  Entry is a child interface of Map and it holds key and value.

What is Map?:  In general a map is a collection of entries. In this example lets see how we iterate java map using entrySet() using for-each loop.

Copy to Clipboard

Output

Copy to Clipboard

3. Approaches after Java 8

3.1. Iterate Java Map using forEach()

forEach() introduced in Java 8 to iterate collections. To know more about java iterator() method read article Java forEach method.

Copy to Clipboard

Output

Copy to Clipboard

3.1. Iterate Java Map using Stream forEach()

Copy to Clipboard

Output

Copy to Clipboard