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.
Below are the most commonly used approaches to iterate Java Map.
- Iterate map using collections Iterator.
- Iterate Java Map using keySet() through for-each loop.
- Iterate Map using entrySet() through for-each loop.
- Iterate Map using java 8 forEach() method, functional style.
- Iterate Map using java 8 Stream forEach() method.
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.
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.
forEach() introduced in Java 8 to iterate collections. To know more about java iterator() method read article Java forEach method.