I am looking for a way to set the default value of a variable depending on whether a value is null or not.
The value in question is a double, and the default value (if that value is null) should be a string.
I tried using the following way but it failed because .orElse expects a double (aka same data type as "value"). Is there any Java methods that I can use to achieve that?
Double value = 8.0;
Optional.ofNullable(value).orElse("not found")
You are not far, just map the value:
String strDouble = Optional.ofNullable(value).map(Objects::toString).orElse("not found");
Since the left side of the the assignment operator can be either a Double
or a String
, the best that can be done is to specify its type as Object
.
This will work:
Object value2 = Optional.<Object>ofNullable(value).orElse("not found");
(i.e. The only shared class in the class hierarchy for Double
and String
is Object)
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