The Wayback Machine - https://web.archive.org/web/20240702073702/https://www.geeksforgeeks.org/iterate-map-java/
Open In App

How to iterate any Map in Java

Last Updated : 13 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report
 

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", "www.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 = www.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", "www.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: www.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", "www.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 = www.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", "www.geeksforgeeks.org");
          
        // forEach(action) method to iterate map
        gfg.forEach((k,v) -> System.out.println("Key = "
                + k + ", Value = " + v));
          
    }
}


Output : 

Key = Quiz, Value = www.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", "www.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 = www.geeksforgeeks.org
Key = Practice, Value = practice.geeksforgeeks.org
Key = GFG, Value = geeksforgeeks.org
Key = Code, Value = code.geeksforgeeks.org

References : Stackoverflow

 



Previous Article
Next Article

Similar Reads

Initialize a static Map using Java 9 Map.of()
In this article, a static map is created and initialised in Java using Java 9. Static Map in Java A static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class. Java 9 feature - Map.of() method In Java 9, Map.of() was introduced which is a convenient way to create instances of Map
2 min read
Program to Iterate over a Stream with Indices in Java 8
Given a Stream in Java, the task is to iterate over it with the help of indices. Examples: Input: Stream = [G, e, e, k, s] Output: [0 -> G, 1 -> e, 2 -> e, 3 -> k, 4 -> s] Input: Stream = [G, e, e, k, s, F, o, r, G, e, e, k, s] Output: [0 -> G, 1 -> e, 2 -> e, 3 -> k, 4 -> s, 5 -> F, 6 -> o, 7 -> r, 8 -> G, 9 -> e, 10 -> e, 11 -> k, 12 -> s] Method
2 min read
Stream iterate(T,Predicate,UnaryOperator) method in Java with examples
The iterate(T, java.util.function.Predicate, java.util.function.UnaryOperator) method allows us to iterate stream elements till the specified condition. This method returns a sequential ordered Stream produced by iterative application of the given next function to an initial element, conditioned on satisfying hasNext predicate passed as parameter.
2 min read
How to iterate over a TreeMap in Java?
Given a TreeMap, the task is to iterate this TreeMap in Java. The TreeMap in Java is used to implement Map interface and NavigableMap along with the Abstract Class. We cannot iterate a TreeMap directly using iterators, because TreeMap is not a Collection. So we will have to use TreeMap.entrySet() method. This method returns a collection-view(Set
3 min read
How to iterate over a 2D list (list of lists) in Java
Given a 2D list, the task is to iterate this 2D list in Java. 2D list (list of lists) The 2D list refers to a list of lists, i.e. each row of the list is another list. [ [5, 10], [1], [20, 30, 40] ] Iterate a 2D list: There are two ways of iterating over a list of list in Java. Iterating over the list of lists using loop: Get the 2D list to the ite
4 min read
Map Values() Method in Java With Examples
Map Values() method returns the Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. Syntax: map.values() Parameter: This method does not take any parameter. Return value: It returns a collection view of all the values present in the map. Exa
2 min read
IntStream map(IntUnaryOperator mapper) in Java
IntStream map(IntUnaryOperator mapper) returns a stream consisting of the results of applying the given function to the elements of this stream. This is an intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, they give a Stream instance as output.
2 min read
Stream map() in Java with examples
Stream map(Function mapper) returns a stream consisting of the results of applying the given function to the elements of this stream. Stream map(Function mapper) is an intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, they give a Stream instance
3 min read
Immutable Map in Java
ImmutableMap, as suggested by the name, is a type of Map which is immutable. It means that the content of the map are fixed or constant after declaration, that is, they are read-only.If any attempt made to add, delete and update elements in the Map, UnsupportedOperationException is thrown.An ImmutableMap does not allow null element either.If any at
6 min read
EnumMap putAll(map) Method in Java
The Java.util.EnumMap.putAll(map) method in Java is used to copy all the mappings from one map to a newer one. Older mappings are replaced in a newer one. Syntax: void putAll(map) Parameters: The method takes one parameter map. It is the map which is to be copied to the newer one. Return Value The method does not return any value. Below programs il
2 min read
three90RightbarBannerImg