I have a HashMap<String,String> (called p2p) and I want to make a loop over its elements. I found the following simple way to do it:
for (String key : p2p.keySet()) {
value = p2p.get(key);
}
However, later I found out that people use iterator(). For example:
Iterator it = p2p.keySet().iterator();
while(it.hasNext()) {
key = it.next();
value = p2p.get(key);
}
For me the first way looks simpler. So, my question is why people use the second way? Does it have some objective advantages or it is just question of taste and subjectivity of the simplicity?
They’re the same – the enhanced for loop uses an iterator to get the elements (unless you’re iterating over an array, in which case it uses the length and array access under the hood.)
Personally, however, I wouldn’t iterate quite that way – I’d iterate over the key/value pairs:
That way you never need to do any actual look-ups.