HashMap to return default value for non-found keys?
In Java 8, use Map.getOrDefault. It takes the key, and the value to return if no matching key is found.
[Update]
As noted by other answers and commenters, as of Java 8 you can simply call Map#getOrDefault(...)
.
[Original]
There's no Map implementation that does this exactly but it would be trivial to implement your own by extending HashMap:
public class DefaultHashMap<K,V> extends HashMap<K,V> {
protected V defaultValue;
public DefaultHashMap(V defaultValue) {
this.defaultValue = defaultValue;
}
@Override
public V get(Object k) {
return containsKey(k) ? super.get(k) : defaultValue;
}
}