Atom Feed SITE FEED   ADD TO GOOGLE READER

Java Minutiae - Map.remove()

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);
}

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):
  if (map.containsKey(key)) {
map.remove(key);
deleteAssociatedFiles(key);
}

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:
  if (map.keySet().remove(key)) {
deleteAssociatedFiles(key);
}


I learned this trick from Jared of the Google Collections team.
Cool! I'd always just ASSumed that the Set returned by keySet was a read-only view.
never thought of that one! but that's jared for you.