The problem with this pattern is that you'd have to somehow define the value that should be used in case the get()
returns null.
There certainly are libraries out there and IIRC there are also some newer collections that do that, but unfortunately I don't remember which those were.
However, you could write a utility method yourself, provided you have a standard way of creating the new values. Something like this might work:
public static <K, V> V safeGet(K key, Map<K,V> map, Class<V> valueClass) throws /*add exceptions*/ {
V value = map.get(key);
if( value == null ) {
value = valueClass.newInstance();
map.put( key, value );
}
return value;
}
Note that you'd either have to throw the reflection exceptions or handle them in the method. Additionally, this requires the valueClass
to provide a no-argument constructor. Alternatively, you could simply pass the default value that should be used.
Java 8 update
It has already been mentioned in other answers but for the sake of completeness I'll add the information here as well.
As of Java 8 there is the default method computeIfAbsent(key, mappingFunction)
which basically does the same, e.g. if the value class was BigDecimal
it could look like this:
BigDecimal value = map.computeIfAbsent(key, k -> new BigDecimal("123.456"));
The implementation of that method is similar to the safeGet(...)
defined above but more flexible, directly available at the map instance and better tested. So when possible I'd recommend using computeIfAbsent()
instead.