When do I need to use Option.orElseGet () compared to Optional.orElse ()

I need a clear explanation, although I read this link, but I do not see any clear clarity. So everyone explains this to me with short code.

+1
source share
2 answers

I think I'm starting to understand your question. The execution order with Optionalmay differ from what we are used to in procedural programming (the same is true for Java threads and other code using lambdas).

I will use two examples from the Eugenes answer :

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

Java: orElse() new MyObject() . , MyObject. orElse(). orElse() , Optional; ( ); , , . .

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

, . . { } ( Should I see this Eugenes). orElseGet , Optional. , , , , . , , { } , , orElseGet().

, a MyObject . a Supplier . , , - . , . MyObject , , , , . Eugene , . , , , - .

+10

:

static class MyObject {
    public MyObject() {
        System.out.println("Creating one..." + this);
    }
}

:

  Optional<MyObject> o1 = Optional.of(new MyObject()); // 7382f612

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

:

 Creating one... MyObject@7382f612
 Creating one... MyObject@1055e4af

, Optional ; orElse - , . orElseGet .

, ; ?

, , :

public T orElseGet(Supplier<? extends T> supplier) {
    return value != null ? value : supplier.get();
}
+6

All Articles