使用JDK1.8的流特性快速操作map实例

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
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

往事不堪回首..

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值