Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getOrDefault for Map<String, ?>

Tags:

java

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?

like image 769
Guichi Ren Avatar asked Jan 23 '26 14:01

Guichi Ren


1 Answers

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.

like image 147
Andy Turner Avatar answered Jan 26 '26 02:01

Andy Turner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!