如何检查布尔值是否为空?

How to check Boolean for null?

我想向检查 Boolean isValue:

的三元运算符添加空值检查
public String getValue() {
    return isValue ? "T" : "F";
}

我的任务是:

What if the Boolean(object) return null? Add a boolean check and return "" (empty String in case if its null).

请注意 isValueBoolean,而不是 boolean

三元运算符具有以下语法:

result = expression ? trueValue : falseValue;

当表达式的计算结果为 true 时返回 trueValue,否则返回 falseValue

如果您想添加一个空检查,这样当 Boolean isValuenull 时,方法 returns "",它不是使用三元运算符非常可读:

String getValue() {
    return isValue == null ? "" : (isValue ? "T" : "F");
}

if语句可以更好地表达这样的语句。该方法的主体将变为

final String result;
if (isValue == null) {
    result = "";
} else if (isValue) {
    result = "T";
} else {
    result = "F";
}
return result;

正如评论中指出的那样,您使用的三元运算符语法不正确,应该是 isValue ? "T" : "F"。我建议使用将三元运算符与标准 if 语句混合的解决方案来检查 null 值。

解决方案如下所示:

public String getValue() {
    if (isValue == null) {
        return "";
    }
    return isValue ? "T" : "F";
}

这将首先检查 null,如果值为 null,则 return 为空 String。否则它将检查正常值和 return TFString 值分别用于 truefalse

你可以

return Optional.ofNullable(isValue).map(t -> t ? "T": "F").orElse("");