Understanding Optional.orElse() vs Optional.orElseGet()
In Java, Optional
provides a way to handle potentially null
values safely. The methods orElse()
and orElseGet()
are used to provide default values when an Optional
is empty. However, the difference between these two methods is important depending on the cost of the default value computation.
Step 1: Define the Default Method
Let's assume we have a method that returns a default value of type String
:
public String getDefault() {
System.out.println("Getting Default Value");
return "Default Value";
}
Step 2: Examine the Two Cases
Case 1: Using orElseGet()
String name = Optional.of(value)
.orElseGet(() -> getDefault());
- Here,
getDefault()
is called only ifvalue
isnull
. This meansgetDefault()
is evaluated lazily (only when needed).
Case 2: Using orElse()
String name = Optional.of(value)
.orElse(getDefault());
- In this case,
getDefault()
is called always, regardless of whethervalue
isnull
or not. This meansgetDefault()
is eagerly evaluated.
Key Difference:
- In Case 1,
getDefault()
will be executed only if theOptional
is empty (i.e.,value
isnull
). - In Case 2,
getDefault()
will be executed every time, even if theOptional
is not empty.
Conclusion:
- If
getDefault()
is not expensive to compute (i.e., it doesn't take a long time), eitherorElse()
ororElseGet()
can be used since the result will be the same. - However, if
getDefault()
is expensive to compute (e.g., involves time-consuming operations), you should prefer Case 1 (usingorElseGet()
), as it ensuresgetDefault()
is only called when necessary.
Message for Readers: Keep learning a little every day, and don't forget to take notes to solidify your understanding!
#Java #Optional #LazyEvaluation
Comments
Post a Comment