如何将Java中使用Stream的服务层代码改写为普通for循环
getValidCoupon方法运行逻辑
该方法的作用是根据传入的查询条件从数据库读取有效的优惠券数据,转换为前端需要的DTO对象集合后返回,完整执行步骤如下:
- 首先调用
repository.findAll(condition.getCondition()),传入查询条件从数据库查询符合要求的Coupon实体集合,再通过toList()方法将查询结果转换为List<Coupon>类型 - 调用
stream()方法将List<Coupon>转换为Java 8 Stream流,用于后续的流式处理 - 执行
map(this::toCouponInfo)对流中的每个Coupon实体做映射转换:逐个调用当前类的toCouponInfo方法,把数据库实体对象转换为接口返回用的CouponInfoDTO对象,转换后流中的元素类型变为CouponResDto.CouponInfo - 最后执行
collect(Collectors.toList()),把处理完成的流重新聚合为List<CouponResDto.CouponInfo>集合,作为方法返回值返回
小提示:当前你的toCouponInfo转换方法没有给CouponInfo的id字段赋值,返回给前端的DTO中id会是默认值null,如果业务需要返回id记得补充setId逻辑
普通for循环改写实现
完全等价于Stream逻辑的for循环写法如下:
public List<CouponResDto.CouponInfo> getValidCoupon(OrderInDto.Search condition) { // 1. 先查询得到数据库实体列表 List<Coupon> couponList = toList(repository.findAll(condition.getCondition())); // 2. 初始化结果列表 List<CouponResDto.CouponInfo> resultList = new ArrayList<>(); // 3. 遍历实体列表逐个转换 for (Coupon coupon : couponList) { CouponResDto.CouponInfo couponInfo = toCouponInfo(coupon); resultList.add(couponInfo); } // 4. 返回结果 return resultList; }
内容的提问来源于stack exchange,提问作者yourGuest
相关产品推荐
相关产品推荐

