Java Tip #7: Minimize Map processing

On to the next Java Tip. Again, this time I'm staying within the boundaries of the Sun JDK.


When traversing a Map, always use the minimum necessary methods to get keys/values out.
<Map>.entrySet() vs. <Map>.keySet() vs. <Map>.values()



 for (String number : phoneBook.keySet()) {
   PhoneBookEntry name = phoneBook.get(number);
   if (name != null) {

 for (String parameterKey : paramMap.keySet()) {
   Object value = paramMap.get(parameterKey);


// if only values are needed
for(PhoneBookEntry name : phoneBook.values()) {
  if (name != null) {

// if key&value are needed
for(Entry<String, Object> entry : paramMap.entrySet()) {
  String parameterKey = entry.getKey();
  Object value = entry.getValue();


Performance gain. Map is only searched once instead twice (and also the hashing for get() is avoided), or there is only the really required data extracted and returned from the map. Furthermore having only the required data around avoids later confusion on the original intent ("... is the key maybe used somewhere or just a leftover?...").




Similar entries