Java Language Optional Return default value if Optional is empty

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Don't just use Optional.get() since that may throw NoSuchElementException. The Optional.orElse(T) and Optional.orElseGet(Supplier<? extends T>) methods provide a way to supply a default value in case the Optional is empty.

String value = "something";

return Optional.ofNullable(value).orElse("defaultValue");
// returns "something"

return Optional.ofNullable(value).orElseGet(() -> getDefaultValue());
// returns "something" (never calls the getDefaultValue() method)
String value = null;

return Optional.ofNullable(value).orElse("defaultValue");
// returns "defaultValue"

return Optional.ofNullable(value).orElseGet(() -> getDefaultValue());
// calls getDefaultValue() and returns its results

The crucial difference between the orElse and orElseGet is that the latter is only evaluated when the Optional is empty while the argument supplied to the former one is evaluated even if the Optional is not empty. The orElse should therefore only be used for constants and never for supplying value based on any sort of computation.



Got any Java Language Question?