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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With