Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

entryset vs keyset in java collection

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`
}
like image 494
Savan Javia Avatar asked Oct 27 '25 14:10

Savan Javia


1 Answers

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.

like image 135
GhostCat Avatar answered Oct 29 '25 02:10

GhostCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!