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 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.