Savan Javia
Savan Javia

Reputation: 319

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`
}

Upvotes: 4

Views: 3998

Answers (1)

GhostCat
GhostCat

Reputation: 140475

It really depends on your requirements. Those sets simply represent three different use cases: if your "iterating" code

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

Related Questions