I am having a variable (testvariable) according to the isNull of the variable I need to make a method call as below
if (testvariable != null)
method(testvariable);
else
method();
What is the best way to simplify the code in Optional
I am having a variable (testvariable) according to the isNull of the variable I need to make a method call as below
if (testvariable != null)
method(testvariable);
else
method();
What is the best way to simplify the code in Optional
Given that your method
function returns a value (is not void
), you can use the map
and orElseGet
functions, like this:
return Optional.ofNullable(testVariable)
.map(tv -> method(tv))
.orElseGet(() -> method());
The map
function transforms your optional to contain the return value of method
, but only if the optional contains a value. If testVariable
was null, then the result will be retrived from the function passed to the orElseGet
method.
If method
returns void
, then don't use Optional
. Optional
is best used to model the presence or absence of a value.