Java9 has added .or
method to Optional. How it is different for existing .orElseGet
?
checkUserInMemory(userId).or(() -> checkUserInDB(userId));
Primarily the return type of both varies.
The call to orElseGet
returns the object T
itself.
throws NullPointerException
if no value is present and the supplying function is null
Use case: To fetch the value deterministically based on the supplied function.
The Optional.or
returns an Optional
describing the value, otherwise returns an Optional
produced by the supplying function
throws NullPointerException
if the supplying function is null
or if the supplying function produces a null
result.
Use case: To chain a series of Optional
s based on the result of the supplied function. Sample -
How do I concisely write a || b where a and b are Optional values?