2

This is my code:

return repository.findFirstByFxDateAndTransCurrAndCrdhldBillCurr(
            LocalDate.parse(request.getDate()), request.getTransactionCurrency(), request.getBillingCurrency())
            .orElse(getCurrencyExchangeRateFromApi(request));

it not work, but I update .orElse to .orElseGet

return repository.findFirstByFxDateAndTransCurrAndCrdhldBillCurr(
            LocalDate.parse(request.getDate()), request.getTransactionCurrency(), request.getBillingCurrency())
            .orElseGet(() -> getCurrencyExchangeRateFromApi(request));

It's work perfectly, I don't know the reason, is that bug of java8 ?

I try to run again many times, nothing change, but I try to write an small example, optional of String instead of from repository, it's ok too.

Stuart Marks
  • 127,867
  • 37
  • 205
  • 259
Loc Le
  • 537
  • 1
  • 8
  • 21

2 Answers2

6

In .orElse(getCurrencyExchangeRateFromApi(request)), getCurrencyExchangeRateFromApi(request) is always executed (regardless of whether the Optional is empty or not).

In .orElseGet(() -> getCurrencyExchangeRateFromApi(request)), getCurrencyExchangeRateFromApi(request) is only executed if the Optional is empty.

If by "not working" you mean you are getting an exception, perhaps there is a problem with your getCurrencyExchangeRateFromApi(request) method.

Eran
  • 387,369
  • 54
  • 702
  • 768
2

Just as Eran mentioned, there is a difference between orElse and orElseGet, no matter what the Optional is the method directly invoked in orElse will be executed while the orElseGet will invoke the supplier if and only if the optional is null.

Here is a small demo:

public class TestOptional {
    public static void main(String... args) {
        Optional<String> val = Optional.ofNullable("Hello");
        String s = val.orElse(test());
        System.out.println(s);
        s = val.orElseGet(() -> test());
        System.out.println(s);
    }

    public static String test() {
        System.out.println("Hello world");
        return "hi";
    }
}

Output:

Hello world
Hello
Hello
Hearen
  • 7,420
  • 4
  • 53
  • 63