javaoption-type

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


Solution

  • 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));