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
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.
By using Optional, we are avoiding null checks and can specify alternate values to return, thus making our code more readable.”
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With