场景: 店铺销量排行榜统计,报表微服务返回List<DTO>如下
public class ShopSaleDto implements Serializable{
private Integer shopId;
private Integer totalSaleNum;
需求:需要返回店铺详情信息及销量
步骤1:取出List<DTO>中的shopId集合调用店铺微服务查询店铺列表,并过滤掉关闭的店铺(lambda表达式简单省略),结果如下
public class ShopInfo implements Serializable {
/*
店铺编号
*/
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@ApiModelProperty(value = "自增")
@Column(name = "id")
private Integer id;
愿景:ShopSaleDto和ShopInfo匹配相同的shopId组装成新的ShopInfoDto对象(该对象包含店铺信息和销量信息)返回给前端
public class ShopInfoDto implements Serializable,Comparable<ShopInfoDto>{
private Integer shopId;
private Integer totalSaleNum;
/**店铺名字**/
private String shopName;
/**店铺头像**/
private String shopAvatar;
代码1:
//将List<ShopSaleDto>转成map,key是唯一值(shop_id)
Map<Integer, ShopSaleDto> dtoMap = list.stream().collect(Collectors.toMap(d -> d.getShopId(), d -> d));
代码2:
//匹配ShopInfoDto
infoList = finalShop.stream().map(s -> {
return toShopInfo(dtoMap.get(s.getId()), s);
}).collect(Collectors.toList());