Suppose you'd like to remove an entry from a Map, and perform some action only if the remove actually removed. Since Map.remove()
returns the value associated with the removed key, we can do this:
if (map.remove(key) != null) {
deleteAssociatedFiles(key);
}`</pre>
Unfortunately, if the map tolerates `null` values, this approach doesn't differentiate between removing 'key→null' and not removing. The standard workaround is to do two map lookups (which fails for [ConcurrentMaps](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ConcurrentMap.html)):
<pre class="prettyprint">` if (map.containsKey(key)) {
map.remove(key);
deleteAssociatedFiles(key);
}`</pre>
But there is an elegant solution. Although `Map.remove()` doesn't know 'null' from 'nothing', it turns out that `Set.remove()` makes the distinction. That method returns `true` only if the set changed. We simply operate on the map's keys, which will write-through:
<pre class="prettyprint">` if (map.keySet().remove(key)) {
deleteAssociatedFiles(key);
}
I learned this trick from Jared of the Google Collections team.