Java - Check Not Null for a number, else assign default string value

coffeeak :

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")
Damián Rafael Lattenero :

You are not far, just map the value:

String strDouble = Optional.ofNullable(value).map(Objects::toString).orElse("not found");

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=125835&siteId=1