使用可选的空检查 [英] Null check using Optional

查看:99
本文介绍了使用可选的空检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Optional Utility在JDK8中执行空检查.这是我正在编写的代码,给我一个错误:

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);

此处可以显示"jcr:description".如果存在,我想在description变量中使用该值,如果为null,则只需设置空白String作为描述.也可以在这里使用Lambda表达式吗?谢谢

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

推荐答案

如果get("jcr:description")的结果可以为null,则不应在其上调用toString(),因为没有任何内容,Optional可以如果使用前的操作已经失败并出现NullPointerException.

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.

您想要的,可以使用:

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

然后您可以将其用作

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("");

然后,总是使用jcr:description的字符串表示形式或空字符串来分配description.

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

如果description不是局部变量,而是字段,则可以使用stringToUse.ifPresent(string -> description = 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.

这篇关于使用可选的空检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆