views:

140

answers:

4

Is there any way to iterate through a java Hashmap and print out all the values for every key that is a part of the Hashmap?

+1  A: 
hashmap.keySet().iterator()

use a for loop to iterate it.

then use hashmap.get(item) to get individual values,

Alternatively just use entrySet() for getting an iterator for values.

Sanjay Manohar
Or, depending on what ping means by "values", `hashmap.values().iterator()`.
Mark Peters
A: 
for (Map.Entry<T,U> e : map.entrySet())
{
    T key = e.getKey();
    U value = e.getValue();
    .
    .
    .
}

In addition, if you use a LinkedHashMap as the implementation, you'll iterate in the order the key/value pairs were inserted. If that's not important, use a HashMap.

Jim Garrison
+4  A: 

Yes, you do this by getting the entrySet() of the map. For example:

Map<String, Object> map = new HashMap<String, Object>();

// ...

for (Map.Entry<String, Object> entry : map.entrySet()) {
    System.out.println("key=" + entry.getKey() + ", value=" + entry.getValue());
}

(Ofcourse, replace String and Object with the types that your particular Map has - the code above is just an example).

Jesper
+2  A: 

With for-each loop, use Map.keySet() for iterating keys, Map.values() for iterating values and Map.entrySet() for iterating key/value pairs.

Note that all these are direct views to the map that was used to acquire them so any modification you make to any of the three or the map itself will reflect to all the others too.

Esko