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`
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With