for (BenefitPackage benefitPackage : packageList) { for (MemberBenefit memberBenefit : benefitPackage.getBenefitList()) { if (memberBenefit.getBenefitNo().equals("RHR041")) { map.put(memberLevel.getLevel(),memberBenefit.getBenefitNo()+"--" + memberBenefit.getBenefitVal()); } } } 优化
时间: 2024-02-10 21:12:29 浏览: 55
这段代码可以进行以下优化:
1. 使用 Lambda 表达式简化代码:
```
packageList.forEach(benefitPackage -> benefitPackage.getBenefitList()
.stream()
.filter(memberBenefit -> "RHR041".equals(memberBenefit.getBenefitNo()))
.forEach(memberBenefit -> map.put(memberLevel.getLevel(), memberBenefit.getBenefitNo() + "--" + memberBenefit.getBenefitVal())));
```
2. 利用 Java 8 中的 Optional 类型避免空指针异常:
```
packageList.forEach(benefitPackage -> benefitPackage.getBenefitList()
.stream()
.filter(memberBenefit -> "RHR041".equals(memberBenefit.getBenefitNo()))
.findAny()
.ifPresent(memberBenefit -> map.put(memberLevel.getLevel(), memberBenefit.getBenefitNo() + "--" + memberBenefit.getBenefitVal())));
```
这样,如果没有找到满足条件的会员福利,就不会执行 `ifPresent` 方法,避免了空指针异常。
阅读全文