Search code examples
javapythondictionaryhashmaphashtable

Java: HashMap: get: specify default value


In Python I can do the following:

d = { 'a': True, 'b': False }
print d.get('x', True)

It will print

True

In Java, the HashMap.get method does not have the second argument for specifying a default value. What is a correct, terse and readable way of achieving this? The following expression seems too redundant to me:

map.containsKey("x") ? map.get("x") : true

Solution

  • Both are wrong because they will do 2 lookups. Generally you'll want to do:

    Boolean ret = map.get("x");
    if (ret == null) {
        return true
    }
    return ret;
    

    You can wrap this in a function

    public static <K,V> V mapGet(Map<K, V> map, K key, V defaultValue) {
        V ret = map.get(key);
        if (ret == null) {
            return defaultValue;
        }
        return ret;
    }
    

    You can make it non-static if you want. If you are the person instantiating the map object (you don't get it from exernal code) you can subclass hashmap. If an API returns map instance then you can't use subclassing.

    public class MyHashMap<K,V> extends HashMap<K,V> {
        public V get(K key, V default) {
            V ret = get(key);
            if (ret == null) {
                return defaultValue;
            }
            return ret;
        }
    }