Programming Tips - Java: How can I get all the values in a HashMap ?

Date: 2012mar30 Language: Java Keywords: enumerate, loop, iterate Q. Java: How can I get all the values in a HashMap ? A. If you have:
HashMap<String, Integer> mymap = new HashMap<String, Integer>();
If you only want the keys...
for (String key : mymap.keySet()) { // ... }
If you only want the values
for (Integer value : mymap.values()) { // ... }
If you want both the keys and values...
import java.util.HashMap; import java.util.Map; for (Map.Entry<String, Integer> entry : mymap.entrySet()) { String key = entry.getKey(); Integer value = entry.getValue(); // ... }
Or you can use an iterator...
Iterator<Map.Entry<String, Integer>> it = mymap.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Integer> entry = it.next(); String key = entry.getKey(); Integer value = entry.getValue(); // ... }
I have read using an iterator is faster but it doesn't look as nice.