今天把写的代码用ChatGPT优化了下,结果chat给我来了个predicate。想研究下看看这个操作,实用性如何。
List<BizExtIntentRefinancingBo> result = bizExtIntentRefinancingService.queryIntentRefinancing(fundCode, stockCode)
.stream()
// 如果是zhangsan:fundCode为空时,返回所有数据;fundCode不为空时,返回fundCode对应的数据
// 如果不是zhangsan:fundCode为空时,返回finalFundcodes中的数据;fundCode不为空时,返回finalFundcodes中的数据并且fundCode对应的数据
.filter(t -> {
if ("zhangsan".equalsIgnoreCase(userInfo.getAccount())) {
if (StringUtils.isEmpty(fundCode)) {
return true;
} else {
return fundCode.equals(t.getFundCode());
}
} else {
if (StringUtils.isEmpty(fundCode)) {
return finalFundcodes.contains(t.getFundCode());
} else {
return finalFundcodes.contains(t.getFundCode()) && fundCode.equals(t.getFundCode());
}
}
})
chat返回的优化结果如下:
// 创建过滤条件
Predicate<BizExtIntentRefinancingBo> filterCondition = t -> {
if ("zhangsan".equalsIgnoreCase(userInfo.getAccount())) {
if (StringUtils.isEmpty(fundCode)) {
return true;
} else {
return fundCode.equals(t.getFundCode());
}
} else {
if (StringUtils.isEmpty(fundCode)) {
return fundcodes.contains(t.getFundCode());
} else {
return fundcodes.contains(t.getFundCode()) && fundCode.equals(t.getFundCode());
}
}
};
// fundCode和fundcodes取交集,使用stream过滤
List<BizExtIntentRefinancingBo> result = bizExtIntentRefinancingService.queryIntentRefinancing(fundCode, stockCode)
.stream()
.filter(filterCondition)
.collect(Collectors.toList());
return result;
}
我的一点思考:
- 如果直接写个private boolean的方法,但是这里用了predicate感觉更简洁。而且没啥复用性,不需要抽出来。
- 看上去更加直观?? 然后去问了下同事,据说这种写法很少见。不知道大家咋说?实际用的多吗?