gpt4 book ai didi

java - 将 ifPresent 与 orElseThrow 结合使用

转载 作者:行者123 更新时间:2023-12-01 07:00:38 26 4
gpt4 key购买 nike

所以我一定错过了一些东西,如果存在可选,我希望执行一个语句 block ,否则抛出异常。

Optional<X> oX;

oX.ifPresent(x -> System.out.println("hellow world") )
.orElseThrow(new RuntimeException("x is null");

如果oX不为空,则打印hello world。如果oXnull则抛出运行时异常。

最佳答案

使用 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");});

关于java - 将 ifPresent 与 orElseThrow 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56573480/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com