How To Iterate Through Map or Hashmap in Java

Iterating over any of the Map implementation(Hashmap, TreeMap etc) is not very straight forward compared to other collections as it is two steps process. There are different ways you can iterate over Map, but in this example we will see how to iterate using advanced for loop and using the Iterator object. We will use following three different ways to traverse.
  • Using Iterator interface
  • Using entrySet() and for loop
  • Using keyset() and for loop
If you want to remove the elements from Hashmap while iterating, then First option suitable for this kind of requirements. The last two will through java.util.ConcurrentModificationException if you remove while iterating.

Java Program to Iterate HashMap

package com.tutorialsdesk.collection;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HashMapIterator {

public static void main(String[] args) {

 Map<String, Integer> map = new HashMap<String, Integer>();

 map.put("ONE", 1);
 map.put("TWO", 2);
 map.put("THREE", 3);
 map.put("FOUR", 4);
 map.put("FIVE", 5);
 System.out.println("Using Iterator");   
 Set<String> setOfKeys = map.keySet();
 Iterator<String> iterator = setOfKeys.iterator();
 while (iterator.hasNext()) {
        String key = (String) iterator.next();
        Integer value = map.get(key);
        System.out.println(key+" :: "+ value);
        //iterator.remove(); 
        //You can remove elements while iterating.   
 }

System.out.println("Using EntrySet");         
for(Map.Entry<String, Integer> maps : map.entrySet()){ 
        System.out.println(maps.getKey() +" :: "+ maps.getValue()); 
        //if you uncomment below code, it will throw
java.util.ConcurrentModificationException             
        //map.remove("FIVE"); 
}

System.out.println("Using KeySet");        
for(String key: map.keySet()){            
        System.out.println(key  +" :: "+ map.get(key));
        //if you uncomment below code, it will throw
java.util.ConcurrentModificationException             
        //map.remove("FIVE"); 
}

 }

 }

Output

Below is the output of above program
Using Iterator
ONE :: 1
TWO :: 2
THREE :: 3
FOUR :: 4
FIVE :: 5
Using EntrySet
ONE :: 1
TWO :: 2
THREE :: 3
FOUR :: 4
FIVE :: 5
Using KeySet
ONE :: 1
TWO :: 2
THREE :: 3
FOUR :: 4
FIVE :: 5

NEXT READ Read and Parse a CSV file in java.
How To Iterate Through Map or Hashmap in Java

Follow us on social media to get latest tutorials, tips and tricks on java.

Please share us on social media if you like the tutorial.
SHARE
    Blogger Comment
    Facebook Comment