1. 背景,我有个货架动态仓位可视化的功能,实现动态生成货架并动态渲染仓位,当生成货架后获取在库数据进行渲染时,因用户有需求鼠标移动到仓位需要显示仓位存储的物料信息,而一个仓位不止有一个物料,因此需要获取所有的在库信息,并使用仓位作为key进行分组,把相同仓位的数据合并成一条进行处理,以下是实现逻辑
/*获取在库信息渲染货架仓位状态(半仓、满仓)、以及添加鼠标划过显示在库物料详情 */
public List<LayoutLibStatus> getList() {
//...获取所有在库数记录 List<LayoutLibStatus> list ,获取方法省略
Map<String, List<LayoutLibStatus>> groupedMap = list.stream().collect(Collectors.groupingBy(LayoutLibStatus::getLocation));//根据仓位进行分组
Map<String, LayoutLibStatus> newMap = groupedMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, // 键为location
e -> {
// Stream<LayoutLibStatus> stream = e.getValue().stream(); 对同一个流做多个操作会抛IllegalStateException: stream has already been operated upon or closed异常
// 筛选e这个List<LayoutLibStatus>中所有实体中属性maxLib最大的那个变量, 如果没有找使用null作为默认值
LayoutLibStatus maxLibEntity = e.getValue().stream().max(Comparator.comparingInt(LayoutLibStatus::getMaxLib)).orElse(null);
//筛选e这个List<LayoutLibStatus>中所有实体的属性acount的总和
int acountSum = e.getValue().stream().mapToInt(LayoutLibStatus::getAcount).sum();
//筛选e这个List<LayoutLibStatus>中所有实体的属性xxx的值使用 ”,“进行拼接
String xxxstr = e.getValue().stream().map(LayoutLibStatus::getxxx).collect(Collectors.joining(","));
Entity l = new Entity();
l.setAcountSum(acountSum);
l.setXxxstr(xxxstr);
return l;
}
));
return new ArrayList<>(newMap.values()); //再把这个返回的newMap转成List
}