When I need to use Optional.orElseGet() over Optional.orElse()

I think I am starting to understand your question. Execution order with Optional can be different from what we are used to in procedural programming (the same is true for Java streams and other code using lambdas).

I will use the two examples from Eugene’s answer:

    o1.orElse(new MyObject()); // 1055e4af 

This is plain old Java: it’s a call to orElse() taking new MyObject() as argument. So the argument is evaluated first and a new MyObject created. This is then passed to orElse(). orElse() looks to see whether a value is present in the Optional; if so it returns that value (discarding the newly created object); if not, it returns the object given to it in the argument. This was the simpler example.

    o1.orElseGet(() -> {
        System.out.println("Should I see this");
        return new MyObject();
    });

Again we have a method call with one argument, and again the argument is evaluated first. The lambda is only created and passed as a supplier. The code inside { } is not executed yet (you also see no Should I see this in Eugene’s output). Again orElseGet looks to see if there is a value present in the Optional. If there is, the value is returned and the supplier we passed is ignored. If there isn’t, the supplier is invoked, the code inside { } is executed to get the value to be returned from orElseGet().

In the first case, one may say that a MyObject is created and wasted. In the second a Supplier is created and wasted. What you get in return is terse and null-pointer safe code in both cases. So very often it’s not important which one you pick. If creating the MyObject is costly or has unwanted side effects, you will of course want the second version where the object is only created when it is asked for, and is never wasted. Eugene in a comment mentions the case where the returned object comes from a database call. Database calls are usually time-consuming enough that you don’t want to make one for no purpose.

Leave a Comment