行业知识
Stream流将List列表中的每个对象赋值给另外一个List列表中的每个对象
2026-12-01 14:54:34
来源:互联网转载
���代码:
()public void repetition(Long id) { // 查询当前用户id Long userId = BaseContext.getCurrentId(); // 根据订单id查询当前订单详情 List orderDetailList = orderDetailMapper.getByOrderId(id); // 将订单详情对象转换为购物车对象 List shoppingCartList = orderDetailList.stream().map(x -> { ShoppingCart shoppingCart = new ShoppingCart(); // 将原订单详情里面的菜品信息重新复制到购物车对象中 BeanUtils.copyProperties(x, shoppingCart, "id"); shoppingCart.setUserId(userId); shoppingCart.setCreateTime(LocalDateTime.now()); return shoppingCart; }).collect(Collectors.toList()); // 将购物车对象批量添加到数据库 shoppingCartMapper.insertBatch(shoppingCartList); } 当使用流操作(stream)遍历订单详情列表并将每个订单详情对象转换为购物车对象时,代码段中的Lambda表达式起着关键作用。让我详细解释一下每一步是如何实现的:
-
使用流操作遍历订单详情列表:
() List orderDetailList = orderDetailMapper.getByOrderId(id);这一行代码首先获取了指定订单id的订单详情列表。然后,使用 .stream() 方法将列表转换为一个流,使得我们可以对列表中的每个元素进行处理。
-
对每个订单详情对象执行转换操作:
List shoppingCartList = orderDetailList.stream().map(x -> { ShoppingCart shoppingCart = new ShoppingCart(); // 将原订单详情里面的菜品信息重新复制到购物车对象中 BeanUtils.copyProperties(x, shoppingCart, "id"); shoppingCart.setUserId(userId); shoppingCart.setCreateTime(LocalDateTime.now()); return shoppingCart; }).collect(Collectors.toList());在这里.map() 方法接收一个函数作为参数,该函数将应用于流中的每个元素。Lambda表达式 x -> { ... } 将每个订单详情对象 x 转换为一个购物车对象,并返回该购物车对象。
-
将结果收集到列表中:
.collect(Collectors.toList());最后,使用 .collect(Collectors.toList()) 方法将转换后的购物车对象收集到一个列表中,并返回该列表。
在每次迭代中,新创建一个购物车对象,并使用 BeanUtils.copyProperties() 方法将订单详情对象的属性复制到购物车对象中。然后设置购物车对象的用户id为当前用户id,创建时间为当前时间。
通过这种方式,对订单详情列表中的每个订单详情对象进行转换,最终得到一个包含所有转换后购物车对象的列表。
上一篇:电脑改定位教程视频
下一篇:总服务器地址怎么查?