Java Optional - If Else Statements

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