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;

该代码进行了以下优化:

  1. 使用 Lambda 表达式简化代码,例如查询失效优惠券的条件语句和排序语句。
  2. 使用 Stream API 优化循环和判断逻辑,例如获取优惠券、过滤失效优惠券和分类优惠券。
  3. 避免在循环中修改集合,使用 Stream API 的 filter 和 collect 操作实现过滤和分类。
  4. 将多个 if 语句合并为一个,减少代码行数。
  5. 使用 try-with-resources 语句关闭资源,确保资源的正确释放。
  6. 使用局部变量,提高代码可读性和维护性。
  7. 简化变量名,提高代码可读性。

通过这些优化,代码更加简洁、高效,并且易于理解和维护。

优惠券优化:高效获取可用优惠券并分类

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

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