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
.