将 ifPresent 与 orElseThrow 一起使用
using ifPresent with orElseThrow
所以我一定遗漏了一些东西,如果存在 Optional,我希望执行一个语句块,否则会抛出异常。
Optional<X> oX;
oX.ifPresent(x -> System.out.println("hellow world") )
.orElseThrow(new RuntimeException("x is null");
如果 oX
不为空则打印 hellow world。
如果 oX
是 null
则抛出运行时异常。
对于Java-8,您可以使用if...else
作为:
if(oX.ifPresent()) {
System.out.println("hello world"); // ofcourse get the value and use it as well
} else {
throw new RuntimeException("x is null");
}
Java-9及以上,可以使用ifPresentOrElse
optional.ifPresentOrElse(s -> System.out.println("hello world"),
() -> {throw new RuntimeException("x is null");});
直接消耗你的元素。
X x = oX.orElseThrow(new RuntimeException("x is null");
System.out.println(x);
或者
System.out.println(oX.orElseThrow(new RuntimeException("x is null"));
已接受的答案 在抛出对象未使用供应商接口实现时存在问题。
为避免这种情况,您可以使用如下所示的 lambda 表达式。
X x = oX.orElseThrow(()-> new CustomException("x is null");
System.out.println(x);
所以我一定遗漏了一些东西,如果存在 Optional,我希望执行一个语句块,否则会抛出异常。
Optional<X> oX;
oX.ifPresent(x -> System.out.println("hellow world") )
.orElseThrow(new RuntimeException("x is null");
如果 oX
不为空则打印 hellow world。
如果 oX
是 null
则抛出运行时异常。
对于Java-8,您可以使用if...else
作为:
if(oX.ifPresent()) {
System.out.println("hello world"); // ofcourse get the value and use it as well
} else {
throw new RuntimeException("x is null");
}
Java-9及以上,可以使用ifPresentOrElse
optional.ifPresentOrElse(s -> System.out.println("hello world"),
() -> {throw new RuntimeException("x is null");});
直接消耗你的元素。
X x = oX.orElseThrow(new RuntimeException("x is null");
System.out.println(x);
或者
System.out.println(oX.orElseThrow(new RuntimeException("x is null"));
已接受的答案 在抛出对象未使用供应商接口实现时存在问题。 为避免这种情况,您可以使用如下所示的 lambda 表达式。
X x = oX.orElseThrow(()-> new CustomException("x is null");
System.out.println(x);