Optional联合Stream使用——集合判空或取值
程序员文章站
2022-06-07 22:46:31
...
jdk8Optional联合Stream使用简单判空取值
原来判断
SspUnionPolicyDetailShowResp showResp = new SspUnionPolicyDetailShowResp();
InterestsCell interestsCell2 = null;
if (ObjectUtils.isNotEmpty(showResp)
&& ObjectUtils.isNotEmpty(showResp.getNonCarInfo())
&& ObjectUtils.isNotEmpty(showResp.getNonCarInfo().getInterestsCellList())) {
List<InterestsCell> interestsCellList = showResp.getNonCarInfo().getInterestsCellList();
for (InterestsCell cell : interestsCellList) {
if (ObjectUtils.isNotEmpty(cell) && StringUtils.equalsIgnoreCase("1", cell.getBenefitName())) {
interestsCell2 = cell;
break;
}
}
}
System.out.println(interestsCell2);
判断为空,若不为空,则取集合里的某个值
SspUnionPolicyDetailShowResp showResp = new SspUnionPolicyDetailShowResp();
String string = Optional.ofNullable(showResp)
.map(SspUnionPolicyDetailShowResp::getNonCarInfo)
.map(SspNonCarPolicyDetailShowResp::getInterestsCellList)
.map(s -> s.stream().filter(Objects::nonNull)
.filter(s1 -> StringUtils.equalsIgnoreCase("1", s1.getBenefitName()))
.map(InterestsCell::getBenefitName)
.findFirst().orElse(null)
)
.orElse(null);
System.out.println(string);
其实第二种代码量并没有少很多,且还不如第一种直观易懂。但是第二种,若使用更高阶的用法,也不失为一种学习的进步。