Optional.ofNullable(变量).orElse(默认值);
例1:求字符串 s 的长度( 为空的时候返回0 )
jdk8前写法:
String s = getKey();
if (s == null) {
return 0;
} else {
return s.length();
}
jdk8写法:
String s = getKey();
return Optional.ofNullable(s).orElse("").length();
例2:循环遍历集合
jdk8前写法:
List<String> list = getList();
if (list != null) {
for(String s: list){
System.out.println(s);
}
}
jdk8写法:
List<String> list = getList();
Optional.ofNullable(list).orElse(new ArrayList<>()).forEach(o -> {
System.out.println(o);
});