Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through a HashMap [duplicate]

What's the best way to iterate over the items in a HashMap?

like image 300
burntsugar Avatar asked Jun 30 '09 23:06

burntsugar


People also ask

Can there be duplicates in a HashMap?

Duplicates: HashSet doesn't allow duplicate values. HashMap stores key, value pairs and it does not allow duplicate keys.


1 Answers

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 values is OK (see Map.Entry).

like image 71
harto Avatar answered Sep 20 '22 17:09

harto