因此,我必须丢失一些东西,如果要使用Optional,我希望执行一个语句块,否则会引发异常。
Optional<X> oX;
oX.ifPresent(x -> System.out.println("hellow world") )
.orElseThrow(new RuntimeException("x is null");
Run Code Online (Sandbox Code Playgroud)
如果oX不为null,则打印hello 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");
}
Run Code Online (Sandbox Code Playgroud)
使用 Java-9 及更高版本,您可以使用 ifPresentOrElse
optional.ifPresentOrElse(s -> System.out.println("hello world"),
() -> {throw new RuntimeException("x is null");});
Run Code Online (Sandbox Code Playgroud)
只需直接消耗您的元素。
X x = oX.orElseThrow(new RuntimeException("x is null");
System.out.println(x);
Run Code Online (Sandbox Code Playgroud)
要么
System.out.println(oX.orElseThrow(new RuntimeException("x is null"));
Run Code Online (Sandbox Code Playgroud)