How to Iterate HashMap in Java Example

In this tutorial, we will learn how to iterate HashMap in Java. Java provides multiple convenient ways to iterate over a hash map.

We can iterate over keys, values, or both. We can also remove an element from a map while iterating over it.

Let’s understand the following ways to iterate HashMap in Java.

Iterating HashMap using Iterator


Let’s take an example program where we will iterate hash map in java using java iterator concept. Look at the following source code.

Program source code 1:

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
public class HashMapIterating1 {
public static void main(String[] args) 
{	
 HashMap<Character, String> hmap = new HashMap<>(); // Creating a hash map.
 
  hmap.put('V', "Violet");
  hmap.put('I', "Indigo");
  hmap.put('B', "Blue");
  hmap.put('G', "Green");
  hmap.put('Y', "Yellow");
  hmap.put('O', "Orange");
  hmap.put('R', "Red");
 
Iterator<Entry<Character, String>> itr = hmap.entrySet().iterator(); // entrySet is a method that is used to get view of entries of a hash map. 
System.out.println("Iterating Entries of HashMap");
while(itr.hasNext())  
{  
 Object key = itr.next();  
 System.out.println(key);  
}
Iterator<Character> itr2 = hmap.keySet().iterator(); // keySet is a method that is used to get view of keys of a hash map.
System.out.println("Iterating Keys of HashMap");
while(itr2.hasNext())
{
 Object keyView = itr2.next();
 System.out.println(keyView);
}
Iterator<String> itr3 = hmap.values().iterator(); // values is a method that is used to get values of keys of a hash map.
System.out.println("Iterating Values of HashMap");
while(itr3.hasNext())
{
 Object valuesView = itr3.next();
 System.out.println(valuesView);
  } 
 }
}
Output:
       Iterating Entries of HashMap
       B=Blue
       R=Red
       V=Violet
       G=Green
       I=Indigo
       Y=Yellow
       O=Orange
       Iterating Keys of HashMap
       B
       R
       V
       G
       I
       Y
       O
      Iterating Values of HashMap
      Blue
      Red
      Violet
      Green
      Indigo
      Yellow
      Orange

Let’s create another program where we will remove the last entry of a hash map returned by the Iterator.

Program source code 2:

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
public class IterationRemove {
public static void main(String[] args) 
{	
 HashMap<Integer, String> hmap = new HashMap<>();
 
  hmap.put(5, "Five");
  hmap.put(10, "Ten");
  hmap.put(15, "Fifteen");
  hmap.put(20, "Twenty");
  hmap.put(25, "Twenty-five");
  hmap.put(30, "Thirty");
 
Iterator<Entry<Integer, String>> itr = hmap.entrySet().iterator(); // entrySet is a method that is used to get view of entries of a map. 
System.out.println("Iterating Entries of HashMap");
while(itr.hasNext())  
{  
  Object key = itr.next(); 
  System.out.println(key);
 }
// Removing last entry returned by Iterator 
  itr.remove(); // This method will remove last entry of a hash map while iterating. 
  System.out.println("Entries of HashMap after removing: " +hmap.entrySet());
 }
}
Output:
      Iterating Entries of HashMap
      20=Twenty
      5=Five
      25=Twenty-five
      10=Ten
      30=Thirty
      15=Fifteen
      Entries of HashMap after removing: [20=Twenty, 5=Five, 25=Twenty-five, 10=Ten, 30=Thirty]

Iterating over keys or values using keySet() and value() methods


This technique is useful when you want to get a set view of keys or values of a hash map. Using keySet(), values(), and for-each loop, you can iterate over keys or values of a hash map.


Let’s take an example program where we will iterate over keys or values of a hash map using keySet() and values() methods.

keySet() method returns a set view of the keys from a hash map and values() method returns a collection-view of values from a hash map.

Program source code 3:

import java.util.HashMap;
public class HashMapIterating2 {
public static void main(String[] args) 
{	
 HashMap<Integer, String> hmap = new HashMap<>();
 
  hmap.put(5, "Five");
  hmap.put(10, "Ten");
  hmap.put(15, "Fifteen");
  hmap.put(20, "Twenty");
  hmap.put(25, "Twenty-five");
  hmap.put(30, "Thirty");
 
for (Integer num : hmap.keySet()) // Iterating over keys of a hashmap using keySet() method.
 System.out.println("Number: " +num);   
 System.out.println();   
	  	   
for (String word : hmap.values()) // Iterating over values of a hashmap using values() method.
 System.out.println("Word: " +word); 
 }
}
Output:
      Number: 20
      Number: 5
      Number: 25
      Number: 10
      Number: 30
      Number: 15

      Word: Twenty
      Word: Five
      Word: Twenty-five
      Word: Ten
      Word: Thirty
      Word: Fifteen

Iterating Java HashMap using Map.Entry<K,V>method


Let’s create a program where we will iterate entry of a hash map using Map.Entry<K,V> method. We will use the following methods for iteration.

Program source code 4:

import java.util.HashMap;
import java.util.Map.Entry;
public class HashMapIterating3 {
public static void main(String[] args) 
{	
 HashMap<Integer, String> hmap = new HashMap<>();
  
  hmap.put(1012, " John");
  hmap.put(1202, " Ricky");
  hmap.put(1303, " Deep");
  hmap.put(1404, " Mark");
  hmap.put(1505, " Maya");
    
for (Entry<Integer, String> entry : hmap.entrySet()) // Iterating over entries of a map using entrySet() method. 
{  
   System.out.println("Id: " + entry.getKey() + ", Name: " + entry.getValue());   
}    
 }
}
Output:
      Id: 1505, Name:  Maya
      Id: 1202, Name:  Ricky
      Id: 1012, Name:  John
      Id: 1303, Name:  Deep
      Id: 1404, Name:  Mark

Iterating Java HashMap using forEach() method


Let’s take an example program based on the forEach() method. This is the best efficient and simple way. In this program, we will use lambda expression inside the forEach() method to display each entry of the hash map.

Program source code 5:

import java.util.HashMap;
public class HashMapIterating4 {
public static void main(String[] args) 
{	
 HashMap<String, String> hmap = new HashMap<>();
  
  hmap.put("India", " Delhi");
  hmap.put("USA", " Washington, D.C.");
  hmap.put("Australia", " Canberra");
  hmap.put("New Zealand", " Wellington");
  hmap.put("Switzerland", " Bern");
    
//Iteration over map using forEach() method.   
   hmap.forEach((k,v) -> System.out.println("Country: "+ k + ", Capital: " + v)); 
 }
}
Output:
      Country: USA, Capital:  Washington, D.C.
      Country: New Zealand, Capital:  Wellington
      Country: Australia, Capital:  Canberra
      Country: Switzerland, Capital:  Bern
      Country: India, Capital:  Delhi

Hope that this tutorial has covered important and basic points related to how to iterate HashMap in Java. I hope that you will have understood this topic.
Thanks for reading!!!
Next ⇒ Internal Working of HashMap in Java 8⇐ PrevNext ⇒

Please share your love