Java流ifPresent orElse / orElseGet

时间:2019-03-06 13:50:48

标签: java java-8 java-stream

你好,我在这里做什么错了

我想获取基础ID,如果基础ID不存在,则获取保险类型..代码片段粘贴在下面..但我在尝试甚至orElseGet()的orElse部分出现错误...它说: Lambda的目标类型必须是接口”。

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());
}

1 个答案:

答案 0 :(得分:0)

在Java-9及更高版本中,您可以简单地使用Optional.orOptional链接为:

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