Monday, January 25, 2016

How to loop over HashMap in Java

In this tutorial, we will show you how to iterate over each entry in HashMap using two methods to display all elements of an HashMap in Java:
  1. Advanced for loop or for each
  2. Iterator + while loop 
In the example below, we are using for loop and iterator with while loop to print out elements:

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

public class IterateHashMap{
 
    public static void main(String[] args) {

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

        map.put("A",1);
        map.put("B",2);
        map.put("C",3);
        map.put("D",4);
        
        //for each loop
        System.out.println("for each:");
        for (Map.Entry mapentry : map.entrySet()) {
           System.out.println("key: "+mapentry.getKey() 
                              + " | value: " + mapentry.getValue());
        }

        //iterator and while loop
        System.out.println("Iterator + while loop");
        Iterator iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
          Map.Entry mapentry = (Map.Entry) iterator.next();
          System.out.println("key: "+mapentry.getKey()
                            + " | value: " + mapentry.getValue());
        } 
    }
}
Execution:

Boucle for:
Key: D | value: 1
Key: A | value: 2
Key: B | value: 3
Key: C | value: 4
Boucle while
Key: D | value: 1
Key: A | value: 2
Key: B | value: 3
Key: C | value: 4
In both cases, we get a set map of key-value data in the object Map.Entry. In for loop, we used entrySet () method of the Map class. In the while loop, was recovered an Iterator object and after obtaining all key-value, then we cast Map.Entry to print the keys and values with both getKey () and getValue () method.

References:
Iterate through a HashMap

No comments:

Post a Comment