tags:

views:

14655

answers:

5

What is the best way to iterate through a HashMap?

+10  A: 

Iterate through the entrySet like so:

public static void printMap(Map mp) {
    Iterator it = mp.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pairs = (Map.Entry)it.next();
        System.out.println(pairs.getKey() + " = " + pairs.getValue());
    }
}

Read more on Map:

http://java.sun.com/j2se/1.4.2/docs/api/java/util/Map.html

karim79
+51  A: 

If you're only interested in the keys, you can iterate through the keySet() of the map:

Map<String, Object> map = ...;

for (String key : map.keySet()) {
    // ...
}

If you only need the values, use values():

for (Object value : map.values()) {
    // ...
}

Finally, if you want both the key and value, use entrySet():

for (Map.Entry<String, Object> entry : map.entrySet()) {
    String key = entry.getKey();
    Object value = entry.getValue();
    // ...
}

One caveat: if you want to remove items mid-iteration, you'll need to do so via an Iterator (see karim79's answer). However, changing item keys and values is OK (see Map.Entry).

harto
According to the documentation, it's more efficient to iterate through the entrySet.
Chochos
@Chochos thanks - updated accordingly.
harto
+1. I've deleted my post, since you've extended yours. :)
Emil H
A: 

Depends. If you know you're going to need both the key and the value of every entry, then go through the entrySet. If you just need the values, then there's the values() method. And if you just need the keys, then use keyset(). A bad practice would be to iterate through all of the keys, and then within the loop, always do map.get(key) to get the value. If you're doing that, then the first option I wrote is for you.

Gary Kephart
+2  A: 

You can iterate through the entries in a Map in several ways. Getting each key and value like this:

Map<?,?> map = new HashMap<Object, Object>();
for(Entry<?, ?> e: map.entrySet()){
 System.out.println("Key " + e.getKey());
 System.out.println("Value " + e.getValue());
}

Or you can get the list of keys with

Collection<?> keys = map.keySet();
for(Object key: keys){
    System.out.println("Key " + key);
    System.out.println("Value " + map.get(key));
}

If you just want to get all of the values, and aren't concerned with the keys, you can use:

Collection<?> values = map.values();
hasalottajava
A: 

Smarter:

for (String key : hashMap.keySet()) {
    System.out.println("Key: " + key + ", Value: " + map.get(key));
}
jkarretero