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?
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 .
The else part of an if-statement is optional, so if the test evaluates to false, then the if-statement does nothing. Braces are optional in the case of a single statement in the body of the if-statement.
How to change this if into Optional? It might be better to take advantage of method overloading in this case, so that the check() method with no parameter calls doMore(), while the check() method with the @NonNull String name only accepts non-null Strings. Otherwise, follow either Eugene's or luk2302's suggestions.
orElse(): returns the value if present, otherwise returns other. orElseGet(): returns the value if present, otherwise invokes other and returns the result of its invocation.
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; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With