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 all the important ways to iterate HashMap.

Iterating HashMap using Iterator


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

Program 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.
 
// Adding entries in 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");

// Creating an Iterator object using iterator() method.
// entrySet is a method that is used to get view of entries of a hash map.
   Iterator<Entry<Character, String>> itr = hmap.entrySet().iterator(); 
   System.out.println("Iterating Entries of HashMap");
   while(itr.hasNext())  
   {  
     Object key = itr.next();  
     System.out.println(key);  
   }
// Iterating over hash map keys.
// keySet is a method that is used to get view of keys of a hash map.
   Iterator<Character> itr2 = hmap.keySet().iterator(); 
   System.out.println("Iterating Keys of HashMap");
   while(itr2.hasNext())
   {
      Object keyView = itr2.next();
      System.out.println(keyView);
   }
// Iterating over values.
// values is a method that is used to get values of keys of a hash map.
   Iterator<String> itr3 = hmap.values().iterator(); 
   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 take another example where we will remove the last entry of a hash map returned by the Iterator.

Program code 2:

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
public class IterationRemove {
public static void main(String[] args) 
{	
// Create a HashMap.
   HashMap<Integer, String> hmap = new HashMap<>();

// Adding entries in 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");

// Here, entrySet is a method that is used to get a view of entries of a map.
   Iterator<Entry<Integer, String>> itr = hmap.entrySet().iterator(); 
   System.out.println("Iterating Entries of HashMap");
   while(itr.hasNext())  
   {  
     Object key = itr.next(); 
     System.out.println(key);
   }
// Removing the last entry returned by Iterator 
   itr.remove(); // This method will remove the 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.

The 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 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");
 
// Iterating over keys of a hashmap using keySet() method.
   for (Integer num : hmap.keySet()) 
     System.out.println("Number: " +num);   
     System.out.println();   
	
// Iterating over values of a hashmap using values() method.  	   
   for (String word : hmap.values()) 
       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 take an example 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 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");
    
// Iterating over entries of a map using entrySet() method.
   for (Entry<Integer, String> entry : hmap.entrySet())  
   {  
      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 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

Iterate HashMap using Stream API in Java 8


Java 8 introduced Stream API that we can use it to iterate over key-value pairs of HashMap. The Stream API is a more compact and functional way to iterate over entries. Let’s take an example:

Program code 6:

import java.util.HashMap;
public class HashMapIterating6 {
public static void main(String[] args) 
{
// Creating a hash map object of key type string and value type integer.	
   HashMap<String, Integer> map = new HashMap<>();

// Adding entries in hash map.   
   map.put("One", 1);
   map.put("Two", 2);
   map.put("Three", 3);
   map.put("Four", 4);
   map.put("Five", 5);

// Using Stream API to itrate over entries.
   map.entrySet().stream().forEach(entry -> { System.out.println(entry.getKey() + " = " + entry.getValue());
   });
 }
}
Output:
      Five = 5
      One = 1
      Four = 4
      Two = 2
      Three = 3

In this example, we have used called the entrySet() method to get a set of key-value pairs. Then, we have called stream() method that returns a sequential stream over the elements in this collection.

The forEach() method iterates over the sequential stream and display entries one by one with the help of getKey() and getValue() method.

Iterate HashMap with Lambda Expression in Java 8


Using lambda expression to iterate over a hashmap is a compact and efficient way to perform some operation on each entry in the HashMap.

It’s also a great way to take benefit from the functional programming features provided by Java 8. We will use forEach() method along with a lambda expression to iterate over hashmap entries. Here’s an example:

Program code 7:

import java.util.HashMap;
public class HashMapIterating7 {
public static void main(String[] args) 
{
// Creating a hash map object of key type string and value type integer.	
   HashMap<String, Integer> map = new HashMap<>();

// Adding entries in hash map.   
   map.put("One", 1);
   map.put("Two", 2);
   map.put("Three", 3);
   map.put("Four", 4);
   map.put("Five", 5);

// Using forEach() method with lambda expression to iterate over hash map.
   map.forEach((key, value) -> System.out.println(key + " = " + value));
 }
}
Output:
       Five = 5
       One = 1
       Four = 4
       Two = 2
       Three = 3

In this tutorial, we have discussed the most important ways to iterate HashMap in Java. Hope that you will have understood the all basic concepts of iterating a hash map and practiced all example programs. In the next, we will learn the internal working of HashMap in Java 8 step by step.
Thanks for reading!!!

⇐ PrevNext ⇒

Please share your love