简体   繁体   中英

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

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")

您不远,只需映射值即可:

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

您编译的方法版本:

Object result = Optional.<Object>ofNullable(value).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");

(ie The only shared class in the class hierarchy for Double and String is Object)

That depends on what you want to do when you have null.

If you can use a default long value - then use your approach and instead of the string put the default value in the orElse .

If you just want to know if a null was passed, and if so do something different, but you don't want to have ==null , you can use the Optional::isPresent call inside an if .

If not having a value is not a state you can tolerate, you can use Optional::orElseThrow to throw an Exception.

Finally, if you just want to do something if you indeed have a value, take a look at Optional::ifPresent - it is the most fitting for this scenario.


If you detail your use-case a bit more, I'll try to fine-tune this answer to fit better.

These are all the APIs for java 8, in later versions you have some more flexibility.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM