可能重复:
如何获取Java中的第一个非null值?
是否可以在Java中执行类似于以下代码的操作
int y = x ?? -1;
Run Code Online (Sandbox Code Playgroud)
我有下面的代码,对于多次空检查有点难看.
String s = null;
if (str1 != null) {
s = str1;
} else if (str2 != null) {
s = str2;
} else if (str3 != null) {
s = str3;
} else {
s = str4;
}
Run Code Online (Sandbox Code Playgroud)
所以我尝试使用Optional.ofNullable如下所示,但如果有人读取我的代码仍然很难理解.在Java 8中这样做的最佳方法是什么.
String s = Optional.ofNullable(str1)
.orElse(Optional.ofNullable(str2)
.orElse(Optional.ofNullable(str3)
.orElse(str4)));
Run Code Online (Sandbox Code Playgroud)
在Java中9,我们可以使用Optional.ofNullable同OR,但在Java8还有没有其他办法?
我无法找到规范的相关部分来回答这个问题.在Java中的条件运算符语句中,是否评估了true和false参数?
因此,以下内容可能会抛出NullPointerException
Integer test = null;
test != null ? test.intValue() : 0;
Run Code Online (Sandbox Code Playgroud) 一个Integer可以null.我将a转换Integer为int:
Integer integer = null;
int i;
try {
i = integer.intValue();
}
catch (NullPointerException e) {
i = -1;
}
Run Code Online (Sandbox Code Playgroud)
有没有更好的办法?
我必须在两个String变量之间进行选择 - 第一个具有非null值.如果它们都是null- 那么我想退出该方法.这可以在以下代码中完成:
String value1 = <get from somewhere>
String value2 = <get from somewhere else>
String target = null;
if (value1 != null) target = value1;
else if (value2 != null) target = value2;
if (target == null) return null;
Run Code Online (Sandbox Code Playgroud)
它也可以用简短的形式完成:
String target = value1 != null ? value1 : value2 != null ? value2 : null;
if (target == null) return null;
Run Code Online (Sandbox Code Playgroud)
我正在努力学习如何以流畅的形式使用Optional
注意:我只能使用Java 8语法(所以没有Optional.or())
我在java中搜索了一段相同的C#'nullable',发现最接近的方法之一是使用包装类; 现在我想知道java中的c#null coalescing运算符(??)是否相等?(当然除了普通的'if'陈述)
我有以下if-else块,我想知道是否有更优雅的方式可以编写此代码...我使用的是Java 8
if(valueString != null) {
return valueString;
}
else if(valueInt != null) {
return String.valueOf(valueInt);
}
else if(valueFloat != null) {
return String.valueOf(valueFloat);
}
else if(valueDate != null){
return String.valueOf(valueDate);
}
else if(valueBit != null) {
return String.valueOf(valueBit);
}
else {
return null;
}
Run Code Online (Sandbox Code Playgroud)