提取ID为数组的部分
List<OrderItemRequest> itemList = lockProductRequest.getOrderItemList(); //一行代码,提取对象里面的id并加入到集合里面 List<Long> productIdList = itemList.stream().map(OrderItemRequest::getProductId).collect(Collectors.toList());
这里直接涉及两个操作,一个是批量查询,一个是优雅的DO与VO的转换!
/** * 批量查询 * @param productIdList * @return */ @Override public List<ProductVO> findProductsByIdBatch(List<Long> productIdList) { List<ProductDO> productDOList = productMapper.selectList(new QueryWrapper<ProductDO>().in("id",productIdList)); List<ProductVO> productVOList = productDOList.stream().map(obj->beanProcess(obj)).collect(Collectors.toList()); return productVOList; }
这里就是分组
//批量查询 List<ProductVO> productVOList = productService.findProductsByIdBatch(productIdList); //分组 此操作优雅酷炫,直接将productVOList变成了一个根据ProductVO.getId作为标识的map,通过操作map的标识操作其中的对象 Map<Long,ProductVO> maps = productVOList.stream().collect(Collectors.toMap(ProductVO::getId, Function.identity()));
较完整代码
private void setProductLatestPrice(List<CartItemVO> cartItemVOList, List<Long> productIdList) { //批量查询 List<ProductVO> productVOList = productService.findProductsByIdBatch(productIdList); //分组 此操作优雅酷炫,直接将productVOList变成了一个根据ProductVO.getId作为标识的map,通过操作map的标识操作其中的对象 Map<Long,ProductVO> maps = productVOList.stream().collect(Collectors.toMap(ProductVO::getId, Function.identity())); //这里就是对cartItemVOList之前传进来的老对象(老商品)进行修改名字、图片、价格,也是较优雅的操作 cartItemVOList.stream().forEach(item->{ ProductVO productVO = maps.get(item.getProductId()); item.setProductTitle(productVO.getTitle()); item.setProductImg(productVO.getCoverImg()); item.setAmount(productVO.getAmount()); }); }
本文作者为DBC,转载请注明。