Java - How to loop through a Map

By xngo on June 23, 2019

In Java, to loop through a Map, you have to first get the Set and then loop through the Set to get its entries.

import java.util.Map;
import java.util.HashMap;
import java.util.Set;
 
public class LoopMap {
 
    public static void main(String[] args) {
 
        // Create a map with values.
        Map<String, Double> hmap = new HashMap<String, Double>();
        hmap.put("pineapple", 4.99);
        hmap.put("banana", 1.85);
        hmap.put("guava", 0.85);
 
        // Get the Set.
        Set< Map.Entry<String, Double> > smap = hmap.entrySet();
 
        // Loop through the Set.
        for (Map.Entry<String, Double> mentry:smap) { 
            System.out.println("key: "+mentry.getKey()+", Value: "+mentry.getValue()); 
        } 
    }
}

Output

key: banana, Value: 1.85
key: pineapple, Value: 4.99
key: guava, Value: 0.85

Github

  • https://github.com/xuanngo2001/java-small/blob/master/src/net/openwritings/java/util/LoopMap.java

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.