Java Optional - If Else Statements

前端 未结 3 597
小蘑菇
小蘑菇 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 05:55

    To take it further, if you have multiple if (optional.isPresent()) or if (obj != null)

    You can do this:

    (getN returns 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

    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();
    
    0 讨论(0)
  • 2020-12-15 06:03

    If you can incorporate the name into the Car constructor, then you can write this:

    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:

    car = optional.map(id -> getCar(id))
                  .orElseGet(() -> {
                      Car c = new Car();
                      c.setName(carName);
                      return c;
                  });
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题