OrElseGet
OrElseGet is a method of the Java Optional class that provides a way to obtain the contained value or generate an alternative lazily. It was introduced in Java 8 as part of the java.util.Optional API, which supports the handling of optional values without resorting to null checks.
The primary behavior of orElseGet is straightforward: if the Optional contains a value, that value is returned
The method signature is public T orElseGet(Supplier<? extends T> other), where T is the type contained in
Example usage can be concise: Optional<String> opt = Optional.ofNullable(name); String display = opt.orElseGet(() -> fetchFromDatabaseOrDefault(name)); If name is present,
Notes: orElseGet may throw unchecked exceptions if the supplier does; checked exceptions are not part of the