Reputation: 319
Which one better for Performance entryset() OR keyset() in Java Collection ?
(I) Using enrtySet() in for each loop
for (Map.Entry<String,Integer> entry : testMap.entrySet()) {
entry.getKey();
entry.getValue();`enter code here`
}
(II) Using keySet() in for each loop
for (String key : testMap.keySet()) {
testMap.get(key);`enter code here`
}
Upvotes: 4
Views: 3998
Reputation: 140475
It really depends on your requirements. Those sets simply represent three different use cases: if your "iterating" code
needs only keys, iterate keySet()
needs access to key + value; use entrySet()
needs the values, use values()
That's it. Meaning: when you just want to print the value of the map, there is no point in working on iterating keys and then getting values for example.
If you need both key+value, I would recommend for clarity to use entrySet()
. Don't worry about performance until you run into real issues. And then start benchmarking your code to understand what happens.
Upvotes: 9