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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 16:06:33  来源:igfitidea点击:

Java Optional - If Else Statements

javaif-statementjava-8optional

提问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 Optionalas following.

您可以使用Optional如下。

Car car = optional.map(id -> getCar(id))
            .orElseGet(() -> {
                Car c = new Car();
                c.setName(carName);
                return c;
            });

Writing with if-elsestatement is imperative style and it requires the variable carto be declared before if-elseblock.

if-else语句编写是命令式的,它需要carif-else块之前声明变量。

Using mapin Optionalis more functional style. And this approach doesn't need variable declaration beforehand and is recommended way of using Optional.

使用mapinOptional是更实用的风格。而且这种方法不需要事先声明变量,推荐使用Optional.

回答by khelwood

If you can incorporate the name into the Carconstructor, 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 ifstatements

即会像这样使用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();