简体   繁体   English

使用Optional进行空检查

[英]Null check using Optional

I want to perform the null check in JDK8 using Optional utility. 我想使用Optional实用程序在JDK8中执行空检查。 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. 这里“jcr:description”可以存在与否。 And if its present I want to use that value in description variable and if null the simply set blank String for description. 如果它存在,我想在描述变量中使用该值,如果为null,则只需设置空白字符串以进行描述。 Also can Lambda expression also can be use here? Lambda表达式也可以在这里使用吗? Thanks 谢谢

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 . 如果get("jcr:description")可以为null ,则不应该在其上调用toString() ,因为没有任何内容,如果在使用之前的操作已经因NullPointerException失败,则Optional可以执行。

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. 然后, description总是被分配,无论是与的字符串表示jcr:description或空字符串。

You can use stringToUse.ifPresent(string -> description = string); 你可以使用stringToUse.ifPresent(string -> description = string); , if description is not a local variable, but a field. ,如果description不是局部变量,而是字段。 However, I don't recommend it. 但是,我不推荐它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM