问题描述
所以,看完书后,我已经看到了
So after some reading I've seen that
if (optional.isPresent()) {
//do smth
}
不是使用Optional的首选方式( http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html ).但是,如果我有这样的if语句:
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:
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?
推荐答案
您可以按以下方式使用Optional
.
You can use Optional
as following.
Car car = optional.map(id -> getCar(id))
.orElseGet(() -> {
Car c = new Car();
c.setName(carName);
return c;
});
使用if-else
语句进行写操作是命令式的,它要求在if-else
块之前声明变量car
.
Writing with if-else
statement is imperative style and it requires the variable car
to be declared before if-else
block.
在Optional
中使用map
是更实用的样式.而且这种方法不需要预先声明变量,是使用Optional
的推荐方法.
Using map
in Optional
is more functional style. And this approach doesn't need variable declaration beforehand and is recommended way of using Optional
.
这篇关于Java可选-如果其他语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!