Search code examples
javajava-8option-typejava-9

Difference between java 9 OR and java 8 orElseGet


Java9 has added .or method to Optional. How it is different for existing .orElseGet ?

checkUserInMemory(userId).or(() -> checkUserInDB(userId));

Solution

  • Primarily the return type of both varies.

    Optional.orElseGet

    • The call to orElseGet returns the object T itself.

    • throws NullPointerException if no value is present and the supplying function is null

    • Use case: To fetch the value deterministically based on the supplied function.

    Optional.or

    • The Optional.or returns an Optional describing the value, otherwise returns an Optional produced by the supplying function

    • throws NullPointerException if the supplying function is null or if the supplying function produces a null result.

    • Use case: To chain a series of Optionals based on the result of the supplied function. Sample - How do I concisely write a || b where a and b are Optional values?