I've read the answers to this question about the difference between Optional.orElse()
and Optional.orElseGet()
.
It seems that orElseGet()
is always more efficient than orElse()
because of lazy evaluation, and it's apparently visible even when benchmarking very simple examples like this one (see part 4): https://www.baeldung.com/java-optional-or-else-vs-or-else-get
So, are there any use cases where it's better to use orElse
rather than 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.
The orElse() method will return the value present in an Optional object. If the value is not present, then the passed argument is returned.
The orElse() method of java. util. Optional class in Java is used to get the value of this Optional instance, if present. If there is no value present in this Optional instance, then this method returns the specified value.
Optional is a new type introduced in Java 8. It is used to represent a value that may or may not be present. In other words, an Optional object can either contain a non-null value (in which case it is considered present) or it can contain no value at all (in which case it is considered empty).
One of the major use cases where it could be preferable would be when you know you need to fall back to a constant (or even an object already created) to default to. I mean, just compare how poor could this be :
int first = Stream.of(1,3,5).filter(i->i%2==0).findFirst().orElseGet(new Supplier<Integer>() {
@Override
public Integer get() {
return 1;
}
});
or its lambda representation
int first = Stream.of(1,3,5).filter(i->i%2==0).findFirst().orElseGet(() -> 1);
which is redundant as compared to
int first = Stream.of(1,3,5).filter(i->i%2==0).findFirst().orElse(1);
Below is the short answer, for a more detailed answer, please check out my stackoverflow answer here
Optional.isPresent()
valueOptional.isPresent() == false
And as the first approach will always get the resource, you might want to consider the second approach when the required resource is expensive to get.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With