Java 可选 - If Else 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34902216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Optional - If Else Statements
提问by uraza
So after some reading I've seen that
所以经过一些阅读后,我看到了
if (optional.isPresent()) {
//do smth
}
is not the preferred way to use Optional (http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html). But if I have an if-statement like this:
不是使用 Optional 的首选方式(http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html)。但是如果我有这样的 if 语句:
if (optional.isPresent()) {
car = getCar(optional.get());
} else {
car = new Car();
car.setName(carName);
}
Is this the best way to do this or is there a more recommended way?
这是最好的方法还是有更推荐的方法?
采纳答案by TheKojuEffect
You can use Optional
as following.
您可以使用Optional
如下。
Car car = optional.map(id -> getCar(id))
.orElseGet(() -> {
Car c = new Car();
c.setName(carName);
return c;
});
Writing with if-else
statement is imperative style and it requires the variable car
to be declared before if-else
block.
用if-else
语句编写是命令式的,它需要car
在if-else
块之前声明变量。
Using map
in Optional
is more functional style. And this approach doesn't need variable declaration beforehand and is recommended way of using Optional
.
使用map
inOptional
是更实用的风格。而且这种方法不需要事先声明变量,推荐使用Optional
.
回答by khelwood
If you can incorporate the name into the Car
constructor, then you can write this:
如果您可以将名称合并到Car
构造函数中,那么您可以这样写:
car = optional.map(id -> getCar(id))
.orElseGet(() -> new Car(carName));
If you must call the setter separately from your constructor, you would end up with something like this:
如果必须与构造函数分开调用 setter,则最终会得到如下结果:
car = optional.map(id -> getCar(id))
.orElseGet(() -> {
Car c = new Car();
c.setName(carName);
return c;
});
回答by wilmol
To take it further, if you have multiple if (optional.isPresent())
or if (obj != null)
更进一步,如果您有多个if (optional.isPresent())
或if (obj != null)
You can do this:
你可以这样做:
(getN returns Optional<Car>
)
(getN 返回Optional<Car>
)
return get1().map(Optional::of)
.orElseGet(() -> get2()).map(Optional::of)
.orElseGet(() -> get3()).map(Optional::of);
I.e. would be like this using if
statements
即会像这样使用if
语句
Optional<Car> car = get1();
if (car.isPresent()){
return car;
}
car = get2();
if (car.isPresent()){
return car;
}
car = get3();
if (car.isPresent()){
return car;
}
return Optional.empty();