Java 可选 - If Else 语句 [英] Java Optional - If Else Statements

查看:33
本文介绍了Java 可选 - If Else 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以经过一些阅读后,我看到了

if (optional.isPresent()) {//做某事}

不是使用 Optional 的首选方式(http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html).但是如果我有这样的 if 语句:

if (optional.isPresent()) {car = getCar(optional.get());} 别的 {汽车 = 新汽车();car.setName(carName);}

这是最好的方法还是有更推荐的方法?

解决方案

您可以使用 Optional 如下.

Car car = optional.map(id -> getCar(id)).orElseGet(() -> {汽车 c = 新汽车();c.setName(carName);返回 c;});

使用if-else 语句是命令式的,它需要在if-else 块之前声明变量car.>

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

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:

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?

解决方案

You can use Optional as following.

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.

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 可选 - If Else 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆