优化后的代码如下:

Map<String, OrdersDetail> productOrderDetailMap = new HashMap<>();
for (OrdersDetail ordersDetail : orderDetailList) {
    productOrderDetailMap.put(ordersDetail.getOrderItem().getProductId(), ordersDetail);
}

for (CouponIsUseDto couponIsUseDto : couponIsUseDtoList) {
    OrdersDetail ordersDetail = productOrderDetailMap.get(couponIsUseDto.getProductId());
    if (ordersDetail != null) {
        couponIsUseDto.setOrderId(ordersDetail.getId());
    }
}

优化思路:将订单详情列表转换为以商品ID为键,订单详情为值的Map,遍历优惠券使用列表时,通过商品ID从Map中获取订单详情,避免了嵌套循环的操作,提高了效率。

Java 代码优化:使用 Map 提高优惠券与订单匹配效率

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

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