How to iterate any Map in Java

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.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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());
        }
    }

    chevron_right

    
    

    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.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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 keys
            for (String url : gfg.values()) 
                System.out.println("value: " + url);
        }
    }

    chevron_right

    
    

    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.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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());
            }
        }
    }

    chevron_right

    
    

    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.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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));
              
        }
    }

    chevron_right

    
    

    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.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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);
            }
        }
    }

    chevron_right

    
    

    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 : Stackoverflow

This 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 contribute.geeksforgeeks.org or mail your article to contribute@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.



My Personal Notes arrow_drop_up