简体   繁体   中英

Null check using Optional

I want to perform the null check in JDK8 using Optional utility. Here is my code I am writing which giving me an error:

java.util.Optional stringToUse = java.util.Optional.of(childPage.getContentResource().getValueMap().get("jcr:description").toString());
stringToUse.ifPresent(description = stringToUse);

Here "jcr:description" can be present or not. And if its present I want to use that value in description variable and if null the simply set blank String for description. Also can Lambda expression also can be use here? Thanks

If the result of get("jcr:description") can be null , you shouldn't invoke toString() on it, as there is nothing, Optional can do, if the operation before its use already failed with a NullPointerException .

What you want, can be achieved using:

Optional<String> stringToUse = Optional.ofNullable(
    childPage.getContentResource().getValueMap().get("jcr:description")
).map(Object::toString);

Then you may use it as

if(stringToUse.isPresent())
    description = stringToUse.get();

if “do nothing” is the intended action for the value not being present. Or you can specify a fallback value for that case:

description = stringToUse.orElse("");

then, description is always assigned, either with the string representation of jcr:description or with an empty string.

You can use stringToUse.ifPresent(string -> description = string); , if description is not a local variable, but a field. However, I don't recommend it.

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