How To Iterate Map In Java?

There are multiple ways to iterate over a Map In Java which we will learn with examples in this post.

Using entrySet() Method

The Map interface has a method called entrySet() which returns a collection view of the map as Map.Entry. Entry is an inner interface of the Map interface.

Using keySet() method

We can retrieve all keys at once using the keySet() method in a Set and then iterate it over to get the associated value.

Using values() method

Unlike keySet() method, we can extract all values at once using the values() method. But we can not backtrack their associated keys. So using this method we can get both keys and values together.

Using iterator() method

We can use the iterator() method that provides an iterator over a collection. The Iterator interface takes the place of the Enumeration interface in the Java Collections Framework. You can use this instead of the ‘for’ loop. You can call the iterator() method in the output of all three methods above.

Complete Program

Output

For all ways except the values() method, the output will be as below. For the values() method way we will just get values, not keys.

We can also use lambda function and Stream concepts which I will cover in the next post.

Thanks for reading.

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.