Guichi Ren
Guichi Ren

Reputation: 67

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?

Upvotes: 3

Views: 3344

Answers (2)

Aviv
Aviv

Reputation: 14517

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-

Upvotes: 0

Andy Turner
Andy Turner

Reputation: 140494

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.

Upvotes: 4

Related Questions