简体   繁体   中英

getOrDefault for Map<String, ?>

Trying to getOrDefault for Map like:

String test = map.getOrDefault("test", "")

But it gives me an error "Required ? but got a String". Anyway to get around this?

The values of a Map<String, ?> could be of any type.

getOrDefault requires the second parameter to be of the same type as the values; there is no value other than null which can satisfy this, because you don't know if that ? is String , Integer or whatever.

Because you are only retrieving a value from the map, you can safely cast to a Map<String, Object> :

Object value = ((Map<String, Object>) map).getOrDefault("key", "");

This is because you are not putting any value into the map which would make calls unsafe later; and any value type can be stored safely in an Object reference.

The implementation of this method returns the given default value (generics - can be any type) if not found (AKA null).

  default V getOrDefault(Object key, V defaultValue) {
        V v;
        return (((v = get(key)) != null) || containsKey(key))
            ? v
            : defaultValue;
    }

documentation link attached: https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#getOrDefault-java.lang.Object-V-

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM