Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 729
Vivek Dhiman Avatar asked Sep 29 '15 10:09

Vivek Dhiman


People also ask

How do you use Optional null check?

Creating Optional objects Also, by using ofNullable , you can create an Optional object that may hold a null value: Optional<Soundcard> sc = Optional. ofNullable(soundcard); If soundcard were null, the resulting Optional object would be empty.

Why we use Optional instead of null check?

By using Optional, we are avoiding null checks and can specify alternate values to return, thus making our code more readable.”

Can you do Optional of null?

of . Remember that Optional. of doesn't accept null values in its parameter. If you try to pass a null value, it will produce a NullPointerException .

Which method can be used to check null on an Optional variable?

Note that we used the isPresent() method to check if there is a value inside the Optional object. A value is present only if we have created Optional with a non-null value. We'll look at the isPresent() method in the next section.


1 Answers

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.

like image 78
Holger Avatar answered Oct 23 '22 19:10

Holger