HashMap to return default value for non-found keys?

后端 未结 14 2191
别跟我提以往
别跟我提以往 2020-11-27 14:05

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

14条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 14:26

    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.

提交回复
热议问题