赞
踩
一般情况下的写法: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 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;
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。