Larry Larry - 1 year ago 102
Java Question

HashMap to return default value for non-found keys?

Is it possible to have a

return a default value for all keys that are not found in the set?

Answer Source

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;
  public V get(Object k) {
    return containsKey(k) ? super.get(k) : defaultValue;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download