How to iterate any Map in Java - GeeksforGeeks

13 May, 2022
There are generally five ways of iterating over a Map in Java. In this article, we will discuss all of them and also look at their advantages and disadvantages.First of all, we cannot iterate a Map directly using iterators, because Map are not Collection. Also before going further, you must know a little-bit about Map.Entry<K, V> interface.Since all maps in Java implement Map interface, following techniques will work for any map implementation (HashMap, TreeMap, LinkedHashMap, Hashtable, etc.)
1. Iterating over Map.entrySet() using For-Each loop :Map.entrySet() method returns a collection-view(Set<Map.Entry<K, V>>) of the mappings contained in this map. So we can iterate over key-value pair using getKey() and getValue() methods of Map.Entry<K, V>. This method is most common and should be used if you need both map keys and values in the loop. Below is the java program to demonstrate it.
Java
// Java program to demonstrate iteration over // Map.entrySet() entries using for-each loop  import java.util.Map;import java.util.HashMap;  class IterationDemo {    public static void main(String[] arg)    {        Map<String,String> gfg = new HashMap<String,String>();              // enter name/url pair        gfg.put("GFG", "geeksforgeeks.org");        gfg.put("Practice", "practice.geeksforgeeks.org");        gfg.put("Code", "code.geeksforgeeks.org");        gfg.put("Quiz", "quiz.geeksforgeeks.org");                  // using for-each loop for iteration over Map.entrySet()        for (Map.Entry<String,String> entry : gfg.entrySet())             System.out.println("Key = " + entry.getKey() +                             ", Value = " + entry.getValue());    }}
Output: 
Key = Quiz, Value = quiz.geeksforgeeks.org
Key = Practice, Value = practice.geeksforgeeks.org
Key = GFG, Value = geeksforgeeks.org
Key = Code, Value = code.geeksforgeeks.org
2. Iterating over keys or values using keySet() and values() methods Map.keySet() method returns a Set view of the keys contained in this map and Map.values() method returns a collection-view of the values contained in this map. So If you need only keys or values from the map, you can iterate over keySet or values using for-each loops. Below is the java program to demonstrate it.
Java
// Java program to demonstrate iteration over // Map using keySet() and values() methods  import java.util.Map;import java.util.HashMap;  class IterationDemo {    public static void main(String[] arg)    {        Map<String,String> gfg = new HashMap<String,String>();              // enter name/url pair        gfg.put("GFG", "geeksforgeeks.org");        gfg.put("Practice", "practice.geeksforgeeks.org");        gfg.put("Code", "code.geeksforgeeks.org");        gfg.put("Quiz", "quiz.geeksforgeeks.org");                  // using keySet() for iteration over keys        for (String name : gfg.keySet())             System.out.println("key: " + name);                  // using values() for iteration over values        for (String url : gfg.values())             System.out.println("value: " + url);    }}
Output:
key: Quiz
key: Practice
key: GFG
key: Code
value: quiz.geeksforgeeks.org
value: practice.geeksforgeeks.org
value: geeksforgeeks.org
value: code.geeksforgeeks.org
3. Iterating using iterators over Map.Entry<K, V> This method is somewhat similar to first one. In first method we use for-each loop over Map.Entry<K, V>, but here we use iterators. Using iterators over Map.Entry<K, V> has it’s own advantage,i.e. we can remove entries from the map during iteration by calling iterator.remove() method.
Java
// Java program to demonstrate iteration over // Map using keySet() and values() methods  import java.util.Map;import java.util.HashMap;import java.util.Iterator;  class IterationDemo {    public static void main(String[] arg)    {        Map<String,String> gfg = new HashMap<String,String>();              // enter name/url pair        gfg.put("GFG", "geeksforgeeks.org");        gfg.put("Practice", "practice.geeksforgeeks.org");        gfg.put("Code", "code.geeksforgeeks.org");        gfg.put("Quiz", "quiz.geeksforgeeks.org");                  // using iterators        Iterator<Map.Entry<String, String>> itr = gfg.entrySet().iterator();                  while(itr.hasNext())        {             Map.Entry<String, String> entry = itr.next();             System.out.println("Key = " + entry.getKey() +                                  ", Value = " + entry.getValue());        }    }}
Output:
Key = Quiz, Value = quiz.geeksforgeeks.org
Key = Practice, Value = practice.geeksforgeeks.org
Key = GFG, Value = geeksforgeeks.org
Key = Code, Value = code.geeksforgeeks.org
4. Using forEach(action) method : In Java 8, you can iterate a map using Map.forEach(action) method and using lambda expression. This technique is clean and fast.
Java
// Java code illustrating iteration// over map using forEach(action) method  import java.util.Map;import java.util.HashMap;  class IterationDemo {    public static void main(String[] arg)    {        Map<String,String> gfg = new HashMap<String,String>();              // enter name/url pair        gfg.put("GFG", "geeksforgeeks.org");        gfg.put("Practice", "practice.geeksforgeeks.org");        gfg.put("Code", "code.geeksforgeeks.org");        gfg.put("Quiz", "quiz.geeksforgeeks.org");                  // forEach(action) method to iterate map        gfg.forEach((k,v) -> System.out.println("Key = "                + k + ", Value = " + v));              }}
Output : 
Key = Quiz, Value = quiz.geeksforgeeks.org
Key = Practice, Value = practice.geeksforgeeks.org
Key = GFG, Value = geeksforgeeks.org
Key = Code, Value = code.geeksforgeeks.org
5. Iterating over keys and searching for values (inefficient) Here first we loop over keys(using Map.keySet() method) and then search for value(using Map.get(key) method) for each key.This method is not used in practice as it is pretty slow and inefficient as getting values by a key might be time-consuming.
Java
// Java program to demonstrate iteration// over keys and searching for values  import java.util.Map;import java.util.HashMap;  class IterationDemo {    public static void main(String[] arg)    {        Map<String,String> gfg = new HashMap<String,String>();              // enter name/url pair        gfg.put("GFG", "geeksforgeeks.org");        gfg.put("Practice", "practice.geeksforgeeks.org");        gfg.put("Code", "code.geeksforgeeks.org");        gfg.put("Quiz", "quiz.geeksforgeeks.org");                  // looping over keys        for (String name : gfg.keySet())         {            // search  for value            String url = gfg.get(name);            System.out.println("Key = " + name + ", Value = " + url);        }    }}
Output: 
Key = Quiz, Value = quiz.geeksforgeeks.org
Key = Practice, Value = practice.geeksforgeeks.org
Key = GFG, Value = geeksforgeeks.org
Key = Code, Value = code.geeksforgeeks.org
References : StackoverflowThis article is contributed by Gaurav Miglani and Abhishek Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
shivam2608
Java-Collections
Java-Map-Programs
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multithreading in Java
Collections in Java
Queue Interface In Java
Initializing a List in Java
LinkedList in Java