JDK8 新特性:判空遍历写法


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);
});


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM