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

Date: 2012mar30 Update: 2025sep30 Language: Java Keywords: enumerate, loop, iterate Q. Java: How can I get all the values in a HashMap A. Here's a full example:
import java.util.HashMap; import java.util.Iterator; import java.util.Map; class Demo { public static final void main(String []args) { // If you have: HashMap<String, Integer> mymap = new HashMap<String, Integer>(); mymap.put("three", 3); mymap.put("two", 2); mymap.put("one", 1); // If you only want the keys: for (String key : mymap.keySet()) { System.out.println("example1: key=" + key); } // If you only want the values: for (Integer value : mymap.values()) { System.out.println("example2: value=" + value); } // If you want both the keys and values: for (Map.Entry<String, Integer> entry : mymap.entrySet()) { String key = entry.getKey(); Integer value = entry.getValue(); System.out.println("example3: " + key + "=" + value); } // 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(); System.out.println("example4: " + key + "=" + value); } // I have read using an iterator is faster but it doesn't look as nice. } }
Output:
example1: key=one example1: key=three example1: key=two example2: value=1 example2: value=3 example2: value=2 example3: one=1 example3: three=3 example3: two=2 example4: one=1 example4: three=3 example4: two=2