Java Optional - If Else Statements

前端 未结 3 608
小蘑菇
小蘑菇 2020-12-15 05:31

So after some reading I\'ve seen that

if (optional.isPresent()) {
    //do smth
}

is not the preferred way to use Optional (http://www.ora

3条回答
  •  天涯浪人
    2020-12-15 06:07

    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.

提交回复
热议问题