I have a Map in my code, where I\'d avoid potential null pointers if the map\'s #get() method returned an empty l
As noted in comments:
Guava's computing map concept was superseded with LoadingCache. Also java 8 introduced to Map interface nice computeIfAbsent default method which doesn't break map contract and features lazy evaluation .
Guava had the idea of a "computing map" which will execute a function to provide a value if it's not present. It was implemented in MapMaker.makeComputingMap; you could now use CacheBuilder - see CacheBuilder.build for more details.
It may be overkill for what you're after - you might be better off just writing a Map implementation which has a Map (using composition rather than extending any particular implementation) and then just return the default if it's not present. Every method other than get could probably just delegate to the other map:
public class DefaultingMap implements Map
{
private final Map map;
private final V defaultValue;
public DefaultingMap(Map map, V defaultValue)
{
this.map = map;
this.defaultValue = defaultValue;
}
@Override public V get(Object key)
{
V ret = map.get(key);
if (ret == null)
{
ret = defaultValue;
}
return ret;
}
@Override public int size()
{
return map.size();
}
// etc
}