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