Alex Rivera | Logout

HashMap to return default value for non-found keys?

Asked 2011-09-22T18:02:50.670
195

Is it possible to have a HashMap return a default value for all keys that are not found in the set?

Edit
Report

2 Answers

162

[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;
  }
}
answered 2011-09-22T18:09:39.930
0

Not directly, but you can extend the class to modify its get method. Here is a ready to use example: http://www.java2s.com/Code/Java/Collections-Data-Structure/ExtendedVersionofjavautilHashMapthatprovidesanextendedgetmethodaccpetingadefaultvalue.htm

answered 2011-09-22T18:05:31.623

Your Answer