Created
July 16, 2014 08:13
-
-
Save aarondai/139961e1801178247055 to your computer and use it in GitHub Desktop.
Java: Iterate Through HashMap
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// If youre only interested in the keys, you can iterate through the keySet() of the 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 values is OK (see Map.Entry). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment