The following example should demonstrate the difference:
String destroyTheWorld() {
// destroy the world logic
return "successfully destroyed the world";
}
Optional<String> opt = Optional.of("Save the world");
// we're dead
opt.orElse(destroyTheWorld());
// we're safe
opt.orElseGet(() -> destroyTheWorld());
The answer appears in the docs as well.
public T orElseGet(Supplier<? extends T> other)
:
Return the value if present, otherwise invoke other and return the result of that invocation.
The Supplier
won't be invoked if the Optional
presents. whereas,
Return the value if present, otherwise return other.
If other
is a method that returns a string, it will be invoked, but it's value won't be returned in case the Optional
exists.