Is it possible to have a HashMap
return a default value for all keys that are not found in the set?
Java 8 introduced a nice computeIfAbsent default method to Map
interface which stores lazy-computed value and so doesn't break map contract:
Map<Key, Graph> map = new HashMap<>();
map.computeIfAbsent(aKey, key -> createExpensiveGraph(key));
Origin: http://blog.javabien.net/2014/02/20/loadingcache-in-java-8-without-guava/
Disclamer: This answer doesn't match exactly what OP asked but may be handy in some cases matching question's title when keys number is limited and caching of different values would be profitable. It shouldn't be used in opposite case with plenty of keys and same default value as this would needlessly waste memory.
You can simply create a new class that inherits HashMap and add getDefault method. Here is a sample code:
public class DefaultHashMap<K,V> extends HashMap<K,V> {
public V getDefault(K key, V defaultValue) {
if (containsKey(key)) {
return get(key);
}
return defaultValue;
}
}
I think that you should not override get(K key) method in your implementation, because of the reasons specified by Ed Staub in his comment and because you will break the contract of Map interface (this can potentially lead to some hard-to-find bugs).