Iterate over a Map in Java

There are many ways to iterate through a Map in Java.
In this tutorial, we will cover the following:

  • Using the for-each loop
  • Using Iterator interface
  • Using Java 8 forEach method

Iterate through Map in Java using the for-each loop

Example

class Test {
    
  public static void main(String[] args) {
    Map<Integer, String> map = new HashMap<>();
    map.put(1, "Java");
    map.put(7, "Python");
    map.put(10, "Ruby");
    map.put(3, "Kotlin");
        
    for (Map.Entry<Integer, String> entry : map.entrySet()) {
      System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
    }
  
  }
}
Output: Key = 1, Value = Java Key = 3, Value = Kotlin Key = 7, Value = Python Key = 10, Value = Ruby
 
Here, we used the entrySet() method that returns a collection-view (Set<Map.Entry<K, V>>) of the mappings contained in this map. And we used entry.getKey() to retrieve the key and entry.getValue() to retrieve the current iteration value.
 
Additionally, check out a tutorial about Java for loops which includes an example of a for-each loop. 

Iterate through Map using Iterator

We can use the Iterator interface to iterate over a Map.

If you need a refresher on interfaces, check out our tutorial on Interface in Java.

Example

class Test {
    
  public static void main(String[] args) {
    Map<Integer, String> map = new HashMap<>();
    map.put(1, "Java");
    map.put(7, "Python");
    map.put(10, "Ruby");
    map.put(3, "Kotlin");
        
    Iterator<Map.Entry<Integer, String>> itr = map.entrySet().iterator();
    
    while (itr.hasNext()) {
      Map.Entry<Integer, String> entry = itr.next();
      System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
    }
  
  }
}
Output: Key = 1, Value = Java Key = 3, Value = Kotlin Key = 7, Value = Python Key = 10, Value = Ruby

Using Java 8 forEach method

Example

class Test {
    
  public static void main(String[] args) {
    Map<Integer, String> map = new HashMap<>();
    map.put(1, "Java");
    map.put(7, "Python");
    map.put(10, "Ruby");
    map.put(3, "Kotlin");
       
    map.forEach((k, v) -> System.out.println("Key = " + k + ", Value = " + v));
  }
}
Output: Key = 1, Value = Java Key = 3, Value = Kotlin Key = 7, Value = Python Key = 10, Value = Ruby
 
Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *