How To Iterate Over a Map In Java

May 09, 2022
Xblog IterateOveraMap



Introduction

Maps are one of the most prominent data structures offered in Java. You must be probably aware that Java does not allow to iterate a map directly using iterators.

It is because the Map interface is not part of a Collection. ­­­­­ To cater to that, Java offers various other ways to iterate over a Map.

In this article, we will be discussing different methods to successfully iterate through the entries of a map in Java.

explore new Java roles

Maps in Java

Maps are without a doubt, one of the most important Data Structures in Java. The Java Map interface, java.util.Map, is used for creating and adding values in a Map.

A Java Map can store keys and values and each key is linked to a specific value. It allows to easily locate a particular value by using the key of assigned to that value. Each key can be mapped to only one value.

Following are the three types of maps available in Java:

  • HashMap
  • TreeMap
  • Linked HashMap

All these types of maps implement the Map interface. A map is not a Collection but it is still considered under the Collections framework. That is why the Map interface does not extend the Collections interface.

Different Methods to Iterate a Map in Java:

1. Using Maps as Collection

A map can be iterated by viewing it as a Collection. Following are the three collection view methods that are used for iteration:

  • entrySet(): This method returns a collection-view of a map, whose elements are from the Map.Entry class. The entry.getKey() method returns the key, and entry.getValue() returns the corresponding value
  • keySet(): It returns all the keys in a map in a form of Set
  • values(): This will return all the values in a map as a Set

· Iterating Maps with entrySet()

The Map.entrySet() method returns a collection-view(Set<Map.Entry<K, V>>) of the mappings contained in the map.

It allows to iterate key-value pair using getKey() and getValue() methods of Map.Entry<K, V>. This is the most common method used to iterate a map in Java. It is the ideal option when you need both map keys as well as values in the loop.

 

Below is the java program demonstrating the use of Map.entrySet() using the For Loop for iterating a HashMap:

01. import java.util.Map;
02. import java.util.HashMap; 
03. class IterationDemo
04. {
05.	public static void main(String[] arg)
06.	{
07.	   Map<String,String> myMap= new HashMap<String,String>();
08.	   myMap.put("1", "Apple");
09.	   myMap.put("2", "Orange");
10.	   myMap.put("3", "Guava");
11.	   myMap.put("4", "Banana");         
12. for (Map.Entry<String,String> entry : myMap.entrySet())
13.	        System.out.println("Key : " + entry.getKey() +
14.	                          " Value : " + entry.getValue());
15.      }
16. }
Output: 

Key: 1 Value: Apple

Key: 2 Value: Orange

Key: 3 Value: Guava

Key: 4 Value: Banana

· Iterating Maps using keySet() and values() methods

Map.keySet() method returns a set view of the keys contained in the map whereas Map.values() method returns a collection-view of the values in the map. Use of these methods should be preferred If you just need keys or values from the map. Both of these methods can be iterated over keyset or values using for-each loop.

 

See the code below demonstrating how to iterate HashMap is Java using keyset() and values() methods:

01. import java.util.Map;
02. import java.util.HashMap; 
03. class  IteratingMap
04. {
05.    public static void main(String[] arg)
06.    {
07.        Map<String,String> myMap = new HashMap<String,String>();
08.       myMap.put("1", "Apple");
09.        myMap.put("2", "Grape");
10.        myMap.put("3", "Pear");
11.        myMap.put("4", "Orange");
12.      for (String myKey : myMap.keySet())
13.            System.out.println("Key : " + myKey);        
14.
15.        for (String myValue : myMap.values())
15.            System.out.println("Value : " + myValue);
16.    }
17. }

Output:

Key: 1

Key: 2

Key: 3

Key: 4

Value: Apple

Value: Pear

Value: Grape

Value: Orange

2. Using iterators

The iterator is an interface used to iterate over a collection. As we can view maps as a collection, they can also be iterated via the iterator.  The iterator interface is also an alternate for Enumeration in Java Collections Framework.

This approach is very similar to using collection view methods. There we used the for-each loop with Map.entrySet() method to get Map.Entry<K, V>, but in this technique, iterators are used. Using iterators over Map.Entry<K, V> offers some considerable benefits due to iterator methods. for example, you can remove entries from a map during iteration using an iterator.remove() method.

 

01. import java.util.Map;
02. import java.util.HashMap; 
03. class UsingIteration
04. public static void main(String args[])  
05. {  
06.   HashMap<Integer, String> myMap = new HashMap<Integer, String>();
07.   //implementing the map interface  
08.   myMap.put(101,"Roger");  
09.   myMap.put(102,"Pam");  
10.   myMap.put(103, "Dave");    
11.   myMap.put(104, "Kim");  
12.   myMap.put(105, "Paul");  
13.   Iterator <Integer> a = myMap.keySet().iterator();       
14.   //keyset method is used here.  
15.   while(a.hasNext())  
16.   {  
17.     int key=(int)a.next();  
18.     System.out.println("ID:  "+ key +" name: "+myMap.get(key));  
19.    }  
20. }
Output:

ID: 101 name: Roger

ID: 102 name: Pam

ID: 103 name: Dave

ID: 104 name: Kim

ID: 105 name: Paul

· Iterating the keys in Map for searching the values

This approach involves using a loop over keys using Map.keySet() method and then searching for a value associated with the key using the Map.get(key) method for each key.

This is the most inefficient and not recommended approach to pursue when you have to iterate a map. The reason that it has made this list is that it is a very straightforward method, fairly easy to implement and can be used for a small map or else it can be very time-consuming.

 

See the code demonstration below:

01. public static void main(String[] arg)
02.    {
03.       Map<String,String> myMap = new HashMap<String,String>();
04.        myMap.put("001", "Adam ");
05.        myMap.put("002", "Steve ");
06.        myMap.put("003", "Carl");
07.        myMap.put("004", " Helm");
08        // loop for iterating the keys
09.        for (String ID : myMap.keySet())
10.        {
11.            // search  for the value
12.            String name = myMap.get(ID);
13.            System.out.println("ID : " + ID + " Name : " + name);
14.        }
15.    }
16.}
Output: 

ID: 001  Name: Adam

ID: 002  Name: Steve

ID: 003  Name: Carl

ID: 004  Name: Helm

3. Using forEach() method

The forEach() method is another technique to iterate a map in Java. It is used to perform an action for each element of the map.

 

The following code snippet shows the Syntax of the method:

public void forEach(Consumer<? super E> action)

The method takes the action to be performed on each element as a parameter. It does not return anything but it throws the NullPointerException if the specified action is null.

 

The following demonstrates the forEach() method. A lambda expression inside the forEach() method is used to print each element of a map. It does not require converting a map to a set of entries which makes this method significantly faster.

01. import java.util.Map;   
02. import java.util.HashMap;   
03. class IterationExample5   
04. {   
05. public static void main(String[] arg)   
06. {   
07. Map<String,String> myMap = new HashMap<String,String>();   
08. myMap.put("101", "Adam");   
09. myMap.put("102", "Kate");
10. myMap.put("103", "Mark");
11. myMap.put("104", "Steve");   
12. //iterating a map using the forEach() method  
13. myMap.forEach((x,y) -> System.out.println("Employee ID : "+ x + " Employee Name 
    : " + y)); 
14.  }   
15. }
Output:

Employee ID: 101  Employee Name: Adam

Employee ID: 102  Employee Name: Kate

Employee ID: 103  Employee Name: Mark

Employee ID: 104  Employee Name: Steve

4. Using Stream API

Stream API is one of the very important features of Java 8. Along with many other uses, it can also be used to iterate a Map in Java.

Stream API is a better option when you have to perform some additional stream processing in the map along with iteration or else it works just like simple forEach() discussed previously.

 

See this code using the entrySet() as the example to demonstrate the working of Stream API:

01. public void UsingStreamAPI(Map<String, Integer> map) {
02.    myMap.entrySet().stream()
03.      // Stream processing statements
04.     .forEach(x -> System.out.println(x.getKey() + ":" + x.getValue()));
05. }

Conclusion

In this article, we have discussed various operations to iterate a Map in Java. All these operations offer some unique features to fulfill your specific requirements.

See Also: Java 8 Collectors toMap

new Java jobs



author

jordan

Full Stack Java Developer | Writer | Recruiter, bridging the gap between exceptional talent and opportunities, for some of the biggest Fortune 500 companies.


Candidate signup

Create a free profile and find your next great opportunity.

JOIN NOW

Employer signup

Sign up and find a perfect match for your team.

HIRE NOW

How it works

Xperti vets skilled professionals with its unique talent-matching process.

LET’S EXPLORE

Join our community

Connect and engage with technology enthusiasts.

CONNECT WITH US