Java Tip #7: Minimize Map processing

On to the next [Java Tip][1]. Again, this time I’m staying within the boundaries of the Sun JDK.


##Advice When traversing a Map, always use the minimum necessary methods to get keys/values out.
*

.entrySet()* vs. *.keySet()* vs. *.values()* ##Code-Example Before … for (String number : phoneBook.keySet()) { PhoneBookEntry name = phoneBook.get(number); if (name != null) { … … for (String parameterKey : paramMap.keySet()) { Object value = paramMap.get(parameterKey); … After … // if only values are needed for(PhoneBookEntry name : phoneBook.values()) { if (name != null) { … … // if key&value are needed for(Entry entry : paramMap.entrySet()) { String parameterKey = entry.getKey(); Object value = entry.getValue(); … ##Benefit 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?…”). ##Remarks None. [1]: http://kosi2801.freepgs.com/cgi-bin/mt-search.cgi?blog_id=8&tag=Java%20Tips&limit=20