Null check using Optional

21,891

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.

Share:
21,891
Vivek Dhiman
Author by

Vivek Dhiman

Updated on July 09, 2022

Comments

  • Vivek Dhiman
    Vivek Dhiman almost 2 years

    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

    • RealSkeptic
      RealSkeptic over 8 years
      Use ofNullable instead of of.
  • Slava Babin
    Slava Babin about 7 years
    Could you please explain why you do not recommend it?