Wednesday, June 22, 2011

The best way to iterate through a HashMap in java.!

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. However, changing item keys and values is OK (see Map.Entry).
 
        //Map -> Set -> Iterator -> Map.Entry -> troublesome
        Iterator iterator=map.entrySet().iterator();
        while(iterator.hasNext()) 
        {
            Map.Entry mapEntry=(Map.Entry)iterator.next();
            System.out.println("The key is: "+mapEntry.getKey() + ",value is :"+mapEntry.getValue());
        }
 
        //more elegant way
        for (Map.Entry<String, String> entry : map.entrySet()) 
       {
            System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
        }
 
        //weired way, but work anyway
        for (Object key: map.keySet()) 
{
            System.out.println("Key : " + key.toString() + " Value : " + map.get(key));
        }
 
Cheers,
varra
 
 

No comments:

Post a Comment