Java 多个String(字符串)判断是否null(空值)
示例:
String s = null;
if (str1 != null) {
s = str1;
} else if (str2 != null) {
s = str2;
} else if (str3 != null) {
s = str3;
} else {
s = str4;
}
优化:
1 stream 方法
String s = Stream.of(str1, str2, str3)
.filter(Objects::nonNull)
.findFirst()
.orElse(str4);
或
public static Optional<String> firstNonNull(String... strings) {
return Arrays.stream(strings)
.filter(Objects::nonNull)
.findFirst();
}
String s = firstNonNull(str1, str2, str3).orElse(str4);
2 三元运算符
String s =
str1 != null ? str1 :
str2 != null ? str2 :
str3 != null ? str3 : str4
;
3 使用 for 循环判断
String[] strings = {str1, str2, str3, str4};
for(String str : strings) {
s = str;
if(s != null) break;
}
标签:Java,String,str3,str2,str1,str4,null From: https://www.cnblogs.com/yizhiamumu/p/16985964.html