简体   繁体   中英

Java Optional - If Else Statements

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 .

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;
              });

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);

Ie 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();

With Java 9 and later you could use the ifPresentOrElse() method .

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

);

This doesn't seem to work since ifPresentOrElse is void method, it won't return anything

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM