Reputation: 1997
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
Upvotes: 8
Views: 50443
Reputation: 298153
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.
Upvotes: 19