Optional常见用法汇总
程序员文章站
2022-03-04 11:35:53
...
Optional常见用法汇总
isPresent()
- 判断Optional 的 value 值是否为null
private static void test(A a){
boolean b = Optional.ofNullable(a).isPresent();
}
orElseThrow()
- 当Optional 为null 时,抛出指定异常
private static void test(A a){
Optional<A> optionalA = Optional.ofNullable(a).orElseThrow(()->new RuntimeException("查询异常"));
}
ofNullable() 和 orElse() 组合使用,可在’对象套对象 '获取属性值时,简化null判断,当其中任意一个对象为空时,取默认值
- 如下面代码,不用再层层判断:
- 对象a是否为空,为空返回默认值,不为空获取对象b;
- 对象b是否为空,为空返回默认值,不为空获取对象c;
- 对象c是否为空,为空返回默认值,不为空获取属性name;
- 取属性name是否为空,为空返回默认值,不为空获取属性值;
public static void main(String[] args) {
A a = new A();
String name = Optional.ofNullable(a).map(A::getB).map(B::getC).map(C::getName).orElse("Tom");
System.out.println(name);
}
of() 与 ofNullable()的区别
- of 不允许传入null,否则抛 java.lang.NullPointerException;
- ofNullable 可以传入null;
orElse() 与 orElseGet()的区别
- 当Optional 为null 和 不为null 时,都会执行orElse;
- 当Optional 为null 时,才会执行 orElseGet();
public class Test {
public static void main(String[] args) {
System.out.println("=======================test2");
test2("tom");
test2(null);
System.out.println("=======================test2");
System.out.println();
System.out.println("=======================test3");
test3("tom");
test3(null);
System.out.println("=======================test3");
}
private static void test2(String name){
String s = Optional.ofNullable(name).map(Test::sayHello).orElse(sayByeBye("jack"));
System.out.println(s);
}
private static void test3(String name){
String s = Optional.ofNullable(name).map(Test::sayHello).orElseGet(()->sayByeBye("jack"));
System.out.println(s);
}
private static String sayHello(String name){
System.out.println("====hello "+ name);
return "hello "+ name;
}
private static String sayByeBye(String name){
System.out.println("====byeBye "+ name);
return "byeBye "+ name;
}
}
执行结果
test2中:当Optional 为null 和 不为null 时,都执行了orElse;
test3中:当Optional 为null 时,才执行 orElseGet();
=======================test2
====hello tom
====byeBye jack
hello tom
====byeBye jack
byeBye jack
=======================test2
=======================test3
====hello tom
hello tom
====byeBye jack
byeBye jack
=======================test3
上一篇: Java8新特性-Optional类
下一篇: Optional的用法-代码案例