Different Ways Of Iterating Map In Java – Including forEach() and stream() Of Java 8


Map in Java is an interface. It stores data as key-value pair. We will learn different ways to iterate over Map including Java 8 stream() and forEach().

Basics of Map

The Map is an interface in Java which can be used to store data as key-value pairs. If we want to store details of a person such as First name, last name, address, and age then we can use Map here from Java. First name, last name, address, and age are keys and the person’s details for these keys are values.

Since Map is an interface, we can not instantiate it. We need to use its implemented classes such as HashMap, TreeMap etc. Please note that the Map interface is not part of the Collection interface.

Below is a sample program –


We can print the entire Map data i.e. key-value pair as shown above but in real-time we may be required to iterate the Map to perform different actions. In this post, we will see different ways of iterating over the Map including Java 8 methods.

Iterating using entrySet() method

Map interface provides a method called entrySet() which returns a Set view of the mappings contained in the map. Entry is an inner static interface of Map.


Iterating using keySet() method

The above method gives us key and value mappings but we can also get all keys using the keySet() method and iterate over it. This method returns a Set of all keys in Map.


Iterating using forEach() method – Java 8

We can directly use the forEach() method of Map introduced in Java 8. With lambda, we can make it shorter.


Iterating using stream() – Java 8

We can also use the stream() method which may be an indirect way of the above method. This method will be useful if you want to perform some actions on data.


Complete Program

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe to my YouTube channel.

Author: Amod Mahajan

A software Tester who is paid to judge products developed by others. Writing technical posts and creating YouTube videos are my hobbies.

Leave a Reply

Please wait...

Subscribe to new posts to become automation expert

Want to be notified when my new post is published? Get my posts in your inbox.