Java Snippet

Optional orElseGet Patterns

Difficulty: Easy

`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.

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

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.