Artjom Prozorov
Artjom Prozorov

Reputation: 127

Optional ifPresent otherwise call another function

I wrote code that works, however I had to create extra lines, is there a way to compress that in one line? The logic: take last page, perform searching function by regex, if not located, take the page before and perform searching function by regex

Optional<String> totalBoxesLastPage = lastPage.locate(INVOICE_TOTAL_AMOUNT_BOXES);
    Optional<String> totalBoxes = totalBoxesLastPage.isPresent() ? 
                                      totalBoxesLastPage : nextToLastPage
                                     .flatMap(p -> p.locate(INVOICE_TOTAL_AMOUNT_BOXES));

Thank you guys

Upvotes: 0

Views: 1113

Answers (3)

misterbee
misterbee

Reputation: 5172

For future searchers who land on this page:

Optional<String> result = primary
   .findResult()                         // Optional<String>) 
   .map(Optional.of)                     // Optional<Optional<String>>
   .orElse(backup.findResult(PATTERN));  // Optional<String>>

Upvotes: 0

Artjom Prozorov
Artjom Prozorov

Reputation: 127

This worked out for me , i was really blind by not seeing .or function

 or(Supplier<? extends Optional<? extends T>> supplier)

 public Optional<String> findBetweenTwo(Page lastPage,Optional<Page> nextToLast,Pattern pattern) {
    return lastPage.locate(pattern).or(() -> nextToLast.flatMap(p -> p.locate(pattern)));
}

Upvotes: 0

Ravindra Ranwala
Ravindra Ranwala

Reputation: 21124

You may use orElseGet with a supplier to call some function which computes the value if the optional is empty. If a value is present, it returns the value, otherwise returns the result produced by the supplying function. In your case you have to pass Supplier<String>. Moreover, your return type after unwrapping the Optional should be a String, not an Optional<String>.

String totalBoxes = totalBoxesLastPage
    .orElseGet(() -> nextToLastPage.flatMap(p -> p.locate(INVOICE_TOTAL_AMOUNT_BOXES))
        .orElseThrow(IllegalStateException::new));

Upvotes: 2

Related Questions