Java Optional - If Else Statements

前端 未结 3 616
小蘑菇
小蘑菇 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: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;
                  });
    

提交回复
热议问题