1

Hello What am I doing wrong here

I want to get the foundation Id , if its not present then get Insurance Type.. the code snippets are pasted below .. but I get an error at the orElse part I even tried orElseGet() ...It says "target type of Lambda must be an interface"..

String type = getFoundationId(companyInsurances).orElse(()->getInsuranceType(insurance, companyInsurances));

private Optional<String> getInsuranceType(Insurance insurance, List<CompanyInsurance> companyInsurances) {
    return InsurancePeriodHelper.findFirstCompanyInsuranceOfType(companyInsurances, CompanyInsuranceType.POLICY_HOLDER.getValue())
             .map(companyInsurance-> insurance.getProduct());
}

private Optional<String> getFoundationId(List<CompanyInsurance> companyInsurances) {
    return InsurancePeriodHelper.findFirstCompanyInsuranceOfType(companyInsurances, CompanyInsuranceType.FOUNDATION.getValue())
            .map(companyInsurance -> companyInsurance.getCompany().getFoundationIdentifier().toString());
}
Jacob G.
  • 28,856
  • 5
  • 62
  • 116
Priya
  • 21
  • 2
  • `.orElse(getInsuranceType(insurance, companyInsurances));` – Hadi J Mar 06 '19 at 13:53
  • I tried that as well and I get .. orElse (java.lang.String) in Optional cannot be applied to (java.util.Optional) – Priya Mar 06 '19 at 13:56
  • 2
    yeah. right! `getFoundationId(...).orElse(getInsuranceType(...).orElse(""));` it's better follow @Ravinda's answer – Hadi J Mar 06 '19 at 14:00
  • Might just be a duplicate of(quite related) https://stackoverflow.com/questions/28514704/chaining-optionals-in-java-8 – Naman Mar 06 '19 at 15:07

1 Answers1

0

With Java-9 and above you could simply chain such Optionals using Optional.or as:

String type = getFoundationId(companyInsurances)
        .or(() -> getInsuranceType(insurance, companyInsurances))
        .orElse("defaultValue");
Naman
  • 27,789
  • 26
  • 218
  • 353