HashMap to return default value for non-found keys?

后端 未结 14 2135
别跟我提以往
别跟我提以往 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<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.

    0 讨论(0)
  • 2020-11-27 14:27

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

    0 讨论(0)
提交回复
热议问题