Skip to content
Sharp

Streams & functional · interview question

Complete the statements about Optional.

Drop-down clozeMedium

Choose the option that best completes each blank.

`optional.orElse(createDefault())` calls `createDefault()`, while `optional.orElseGet(this::createDefault)` calls it . To throw a custom exception when the Optional is empty, use .

Answer and explanation

Correct answer

optional.orElse(createDefault()) always calls createDefault(), while optional.orElseGet(this::createDefault) calls it only when the Optional is empty. To throw a custom exception when the Optional is empty, use orElseThrow(() -> new NotFoundException()).

Why

Prefer orElseGet when the default is expensive or has side effects.

Test yourself on Streams & functional

A free test with instant, explained results. No account needed.

Start free test