当前位置:   article > 正文

java 判断 string null_Java 多个String(字符串)判断是否null(空值)简单方法代码

filter怎么判断string

一般情况下的写法: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;

}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/45581
推荐阅读
相关标签
  

闽ICP备14008679号