Iterating a HashMap

We know that, Java HashMap class implements the map interface by using a hashtable. It inherits AbstractMap class and implements Map interface.
The important points about Java HashMap class are:
  • A HashMap contains values based on the key.
  • It contains only unique elements.
  • It may have one null key and multiple null values.
  • It maintains no order.
Many times we have to iterate hash map for key or value or both key&value.
Here is code block to iterate for the same...

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();
    // ...
}
 
 
Have Fun!!!
Happy Coding!!! 

Comments

Popular posts from this blog

Android library for displaying complex data structures - "TableView"

Privacy Policy for AndroStockpile