可选的获取价值(如果存在) [英] Optional get value if present
问题描述
作为一个例子,我有一个像这样的可选内容:
As an example I have an optional like this:
Optional<Desktop> opt = Optional.ofNullable(status).map(Status::getDesktop);
我想拥有桌面并在lambda表达式之外使用它.我是这样的:
I want to have the desktop and work with it outside of lambda expressions. I do it like this:
if (opt.isPresent()){
Desktop desktop = opt.get();
...
}
是否有更好的解决方案来获得台式机?像这样的东西?
Is there a better solution to get the desktop; something like this ?
Desktop desktop = Optional.ofNullable(status).map(Status::getDesktop).ifPresent(get());
OrElse是我正在寻找的方法:)
OrElse was the method I was looking for :)
推荐答案
如果您的Desktop
具有默认值,则可以尝试使用Optional.orElse
:
If you have a default value for your Desktop
, you could try with Optional.orElse
:
Desktop defaultDesktop = ...;
Desktop desktop = Optional.ofNullable(status)
.map(Status::getDesktop)
.orElse(defaultDesktop);
但是,您不一定必须在Optional.ifPresent
的lambda表达式内工作.您可以完美地使用接收Desktop
实例的方法,该方法将充当Optional.ifPresent
的Consumer
参数:
However, you don't have to necessarily work inside a lambda expression with Optional.ifPresent
. You could perfectly use a method that receives a Desktop
instance, which would act as the Consumer
argument of Optional.ifPresent
:
Desktop desktop = Optional.ofNullable(status)
.map(Status::getDesktop)
.ifPresent(this::workWithDesktop);
然后:
void workWithDesktop(Desktop desktop) {
// do whatever you need to do with your desktop
}
如果您需要其他参数(除了桌面本身),则可以使用lambda表达式来调用该方法:
If you need additional arguments (apart from the desktop itself), you could use a lambda expression that invokes the method instead:
String arg1 = "hello";
int arg2 = 10;
Desktop desktop = Optional.ofNullable(status)
.map(Status::getDesktop)
.ifPresent(desktop -> this.workWithDesktop(desktop, arg1, arg2));
然后:
void workWithDesktop(Desktop desktop, String arg1, int arg2) {
// do whatever you need to do with your desktop, arg1 and arg2
}
这篇关于可选的获取价值(如果存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!