When to use Optional.orElse() rather than Optional.orElseGet()
- In most cases, you type less when using
orElse
, since it is shorter thanorElseGet
and, compare the signatures of them:
orElse(T other)
orElseGet(Supplier<? extends T> other)
a Supplier<? extends T> other
is most likely longer than T other
. If the performance is not so critical you may choose to type less. Programmer's effort also counts :-) For example, compare:
orElseGet(() -> 1)
orElse(1)
- As your link has mentioned:
by default, it makes more sense to use orElseGet() every time unless the default object is already constructed and accessible directly.
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);