Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Optional - If Else Statements

Tags:

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?

like image 962
uraza Avatar asked Jan 20 '16 14:01

uraza


People also ask

How do you do if else with Optional in Java?

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 .

Is else Optional in if statement?

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 do I replace if else with Optional?

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.

What is the difference between orElse and orElseGet?

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.


2 Answers

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.

like image 105
TheKojuEffect Avatar answered Sep 21 '22 15:09

TheKojuEffect


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;               }); 
like image 20
khelwood Avatar answered Sep 20 '22 15:09

khelwood