Green 绿色
Green 绿色

Reputation: 2886

OptionalInt - Creating Nested orElse() branch

Is there a concise pipeline-like pattern for Java's optional when having something like if - else if - else-like structures?

For example, we have two functions returning OptionalInts, and we want to use the result of f, if present, otherwise the result of g, if present, and otherwise 0:

OptionalInt f(...) {
    return ...
}

OptionalInt g(...) {
    return ...
}


int res = f(...).orElse(g(...).orElse(0));

Is there a more pipline-like structure of this pattern, e.g. (pseudocode)

int res = f(...)
    .orElseTry(g(...))
    .otherwise(0);

Upvotes: 0

Views: 148

Answers (1)

Alexander Ivanchenko
Alexander Ivanchenko

Reputation: 28988

With OptionalInt you can use orElseGet() (credits to @Ole V.V. since he has pointed it out in the comments earlier):

int res = f().orElseGet(() -> g().orElse(0));

In case if there are more than two sources for producing result, you can use the following approach:

int res = Stream.<Supplier<OptionalInt>>of(
        () -> f(),
        () -> g(),
        ...                           // other sources for producing the optional result    
    )                                 // Stream<Supplier<OptionalInt>>
    .map(Supplier::get)
    .filter(OptionalInt::isPresent)  // Stream<OptionalInt>>
    .mapToInt(OptionalInt::getAsInt) // IntStream
    .findFirst()                     // OptionalInt
    .orElse(0);

Upvotes: 1

Related Questions