优化建议:

1.使用lambda表达式简化代码。

2.使用stream API优化循环和判断逻辑。

3.避免在循环中修改集合,可以使用迭代器或者其他方式。

4.将多个if语句合并为一个,减少代码行数。

5.将重复的代码封装成方法,提高复用性。

6.尽量使用局部变量,避免使用全局变量。

7.简化变量名,提高可读性。

8.使用try-with-resources语句关闭资源。

优化后的代码如下:

List<YxStoreCouponIssue> couponList = new ArrayList<>();
for (Long productId : productIds) {
    //根据商品id查询发布的商品优惠券和通用券
    List<YxStoreCouponIssue> couponIssueList = localCache.get(productId);
    if (CollectionUtil.isEmpty(couponIssueList)) {
        couponIssueList = this.baseMapper.productCoupon(productId);
    }
    couponList.addAll(couponIssueList);
}
//去除重复的优惠券
couponList = couponList.stream().distinct().collect(Collectors.toList());
//查询已经使用、过期、失效的优惠券
List<YxStoreCouponUser> failCouponList;
try (LambdaQueryWrapper<YxStoreCouponUser> wrapper = new LambdaQueryWrapper<YxStoreCouponUser>()
        .eq(YxStoreCouponUser::getUid, userId)
        .eq(YxStoreCouponUser::getIsDel, CommonEnum.DEL_STATUS_0.getValue())
        .eq(YxStoreCouponUser::getIsFail, CouponEnum.FALI_0.getValue())
        .ge(YxStoreCouponUser::getEndTime, new Date())) {
    failCouponList = couponUserService.list(wrapper);
}
//过滤已使用、过期、失效的优惠券
couponList = couponList.stream().filter(coupon ->
        failCouponList.stream().noneMatch(failCoupon -> failCoupon.getCid().equals(coupon.getId())))
        .collect(Collectors.toList());
//根据价格排序
couponList = couponList.stream().sorted(Comparator.comparing(YxStoreCouponIssue::getCouponPrice).reversed())
        .collect(Collectors.toList());
//区分商品券和通用券
List<YxStoreCouponIssue> commonCouponList = couponList.stream().filter(coupon ->
        coupon.getCtype().equals(CouponEnum.TYPE_0.getValue())).collect(Collectors.toList());
List<YxStoreCouponIssue> productCouponList = couponList.stream().filter(coupon ->
        coupon.getCtype().equals(CouponEnum.TYPE_1.getValue())).collect(Collectors.toList());
CouponConfirmOrderVo couponConfirmOrder = new CouponConfirmOrderVo();
couponConfirmOrder.setCommonCouponList(commonCouponList);
couponConfirmOrder.setProductCouponList(productCouponList);
return couponConfirmOrder;
``
优化代码 ListYxStoreCouponIssue couponIssueUsersLists = new ArrayList; ListYxStoreCouponIssue commonCouponList = new ArrayList; ListYxStoreCouponIssue productCouponList = new ArrayList;

原文地址: https://www.cveoy.top/t/topic/gpxj 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录