版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
在工作中,经常会处理各种变量,但往往会在使用变量的时候,要进行空判断,不然要报错。
Java 8 提供了判空写法:
Optional.ofNullable(变量).orElse(默认值);
例1:求字符串 s 的长度( 为空的时候返回0 )。
常规写法:
-
String s = getKey();
-
if (s ==
null) {
-
return
0;
-
}
else {
-
return s.length();
-
}
Java 8 写法:
-
String s = getKey();
-
return Optional.ofNullable(s).orElse(
"").length();
例2:循环遍历集合
常规写法:
-
List<String> list = getList();
-
if (list !=
null) {
-
for(String s: list){
-
System.out.println(s);
-
}
-
}
Java 8 写法:
-
List<String> list = getList();
-
Optional.ofNullable(list).orElse(
new ArrayList<>()).forEach(o -> {
-
System.out.println(o);
-
});