Aug 17, 2012

Java - Iterating Java HashMap Oject

Let create the Object. HashMap<String, Object> map = new HashMap<String, Object>();
for (String key : map.keySet()) {
    System.our.println("My HashMap Key"+key);
}
If you only need the values, use values():
for (Object value : map.values()) {
    System.our.println("My HashMap Vaslue"+value.toString()); // I issue toString to convert the object into String value
}
Finally, if you want both the key and value, use entrySet():
for (HashMap.Entry<String, Object> entry : map.entrySet()) {
    String key = entry.getKey();
    Object value = entry.getValue();
    // ... Print here if you want or do something
}

No comments: