Code Snippets
/

Optional orElseGet Patterns

Optional orElseGet Patterns

`Optional` makes the absence of a value explicit, but the `orElse` vs `orElseGet` choice trips people up. This snippet contrasts the two, shows `orElseThrow` for required-value contracts, and demonstrates `map`/`flatMap` chaining for null-safe field access. Reach for `orElseGet` whenever the default is expensive to compute.

Java
Easy
3 snippets
java-optionals
error-handling
implementation

1,068 views

13

import java.util.Optional;

public class Main {
    static String expensiveDefault() {
        System.out.println("  computing default...");
        return "FALLBACK";
    }

    public static void main(String[] args) {
        Optional<String> present = Optional.of("value");

        System.out.println("orElse on present:");
        String a = present.orElse(expensiveDefault()); // ALWAYS evaluates the arg
        System.out.println("  -> " + a);

        System.out.println("orElseGet on present:");
        String b = present.orElseGet(Main::expensiveDefault); // ONLY runs if empty
        System.out.println("  -> " + b);

        System.out.println("orElseGet on empty:");
        String c = Optional.<String>empty().orElseGet(Main::expensiveDefault);
        System.out.println("  -> " + c);
    }
}

orElse(value) evaluates its argument unconditionally, even when the Optional is non-empty. That is fine for a literal or cached value but wasteful when the fallback requires a network call or heavy computation. orElseGet(Supplier) is lazy: it only invokes the supplier when the Optional is actually empty. Always prefer orElseGet when the default has any cost, and reserve orElse for cheap constants like "" or 0.