I am sick of the following pattern:
value = map.get(key);
if (value == null) {
value = new Object();
map.put(key, value);
}
This ex
EDIT : Note that the feature mentioned below is long deprecated, and a CacheBuilder should be used instead.
The Guava library has a "computing map", see MapMaker.makeComputingMap(Function).
Map map = new MapMaker().makeComputingMap(
new Function() {
public String apply(Stringt) {
return new Object();
}
});
If you need the Function several times, extract it into a utility class, and then create the Map like this (where MyFunctions.NEW_OBJECT is the static Function instance):
Map map = new MapMaker()
.makeComputingMap(MyFunctions.NEW_OBJECT);