本文主要介绍Java中,同时判断多个字符串是否为空值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;
}

推荐文档

相关文档

大家感兴趣的内容

随机列表