roman roman -4 years ago 136
Java Question

Optional.ifPresent (what if not)

I'm trying to build a flow based on options returned by methods.

My question is: Is there a way to build a flow that splits in case of getting for example

Optional<int> (some)
and executing another flow in the other case in a nice way? (not of using if else switch ternary )

Answer Source

I think what you're looking for is orElseGet:

The following returns 6:

Optional.of(5).map(value -> value + 1)
              .orElseGet(() -> 1);

And this will return 1:

Optional.<Integer>empty().map(value -> value + 1)
                         .orElseGet(() -> 1)

orElseGet is takes a supplier, so you can execute arbitrary code in there so long as you return a value.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download