JDK 1.8新特性,Lamda表达式,steam流的一些用法例子

1.返回集合的某个字段集

List<MaThtZjConfigEntity> data = new ArrayList<>()
List<String> position = null;
if (!CollectionUtils.isEmpty(data)) {
    position = data.stream().map(MaThtZjConfigEntity::getZjType).distinct().collect(Collectors.toList());
}

2.两种写法代替for循环直接赋值

// 先过滤,后累加
List<SmtEfficiencyDto> tempList = JSONArray.parseArray(RedisKit.use().get(redisKey), SmtEfficiencyDto.class);
           tempList.stream().filter(
                            t -> workLines.contains(t.getWorkLine())).collect(Collectors.toList())
                    .stream().forEach(
                            t -> {
                    SmtEfficiencyDto mapValue = smtEfficiencyMap.get(t.getCumulativeDate());
                    if (mapValue != null) {
                        mapValue.setProdNum(Math.max(mapValue.getProdNum(),0) + t.getProdNum());
                        mapValue.setInputTime(Math.max(mapValue.getInputTime(),0) + t.getInputTime());
                        mapValue.setOutputTime(Math.max(mapValue.getOutputTime(),0) + t.getOutputTime());
                        mapValue.setOutputDevicesNum(Math.max(mapValue.getOutputDevicesNum(),0) + t.getOutputDevicesNum());
                    }});


            // 计算SMT生产效率
Map<String, SmtEfficiencyDto> smtEfficiencyMap = initCoordinateAxis(startDate, endDate);
            smtEfficiencyMap.values().stream().forEach(
                    t -> t.setRate(t.getInputTime() <= 0
                            ? t.getInputTime()
                            : BigDecimal.valueOf(t.getOutputTime())
                            .divide(BigDecimal.valueOf(t.getInputTime()), 4, BigDecimal.ROUND_HALF_UP)
                            .doubleValue()));

3.流里面操作一些赋值代替for循环

   if (orderCompletionRates != null && orderCompletionRates.size() > 0) {
                String cumulativeDate = startDate.substring(0,10);

                orderCompletionRates.stream().forEach(t -> {
                    t.setCumulativeDate(cumulativeDate);
                    t.setIsCompleted(t.getReportCount() == t.getPlanProdCount() ? COMPLETE_STATUS : INCOMPLETE_STATUS);
                });

                this.storeSmtOrThtOrderCompletionRateIntoDatabase(orderCompletionRates);
            }

4.map用流处理

     if (materialPrepCompletionRateList != null && materialPrepCompletionRateList.size() > 0) {
            Map<String, List<MaterialPrepCompletionRate>> materialPrepCompletionRateMap = new HashMap<>(3);

            materialPrepCompletionRateList
                .forEach(element -> {
                    String key = element.getMenucode();
                    if (materialPrepCompletionRateMap.containsKey(key)) {
                        materialPrepCompletionRateMap.get(key).add(element);
                    } else {
                        List<MaterialPrepCompletionRate> materialPrepCompletionRates = new ArrayList<>(256);
                        materialPrepCompletionRateMap.put(key, materialPrepCompletionRates);
                    }
                });

            /**
             * 实际存入REDIS中的数据标识时间为当前班次的开始时间
             */
            final String selDate =
                ShiftTimeUtil.DATETIME_FORMAT.format(
                    ShiftTimeUtil.addDays(ShiftTimeUtil.DATETIME_FORMAT.parse(startDate), -1));

            // 循环遍历map,将明细数据按照KEY为仓别值为明细列表存入到REDIS中
            if (!materialPrepCompletionRateMap.isEmpty()) {
                materialPrepCompletionRateMap
                    .entrySet()
                    .forEach(element -> {
                        String key = element.getKey().concat(":").concat(DzKanBanName.MATERIAL_PREP_COMPLETION_RATE).concat(":").concat(selDate);
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("dataList", element.getValue());
                        jsonObject.put("configs", materialOperateDao.findMaterialOperatorConfig(element.getKey()));
                        RedisKit.use().set(key, jsonObject.toJSONString());
                        RedisKit.use().expire(key, 13 * 3600);
                    });
            }
        }

5.返回map的用法

     //查询出物料相关的全部信息(物料 基地 是否管控标志 物料组 预警时间 存储时间等)
        List<MaBatchControlMaterialInfoEntity> materialInfoList = maBatchControlMapper.getMaBatchControlMaterialInfo();
        //key:物料+基地 value:实体类
        Map<String, MaBatchControlMaterialInfoEntity> materialInfoMap = materialInfoList.stream().collect(Collectors.toMap(k -> k.getWerks() + "_" + k.getMatnr(), k -> k));


  //按照工厂或者线体分组
 Map<String, List<WorkInProcessResultDto>> codeMap = resultList.stream().collect(groupingBy(WorkInProcessResultDto::getAufnr));

//先循环工厂或者线体
            for (Map.Entry<String, List<WorkInProcessResultDto>> entry : codeMap.entrySet()) {
                String key = entry.getKey();
  List<WorkInProcessResultDto> list = entry.getValue();

}

6.去重

resultList = resultList.stream().distinct().collect(Collectors.toList());

7.将一个集合赋给另外一个集合

 List<MaBatchStatusExportWriteModel> collect = list.parallelStream().map(entity -> {
            MaBatchStatusExportWriteModel model = new MaBatchStatusExportWriteModel();
            model.setWerks(entity.getWerks());
            model.setLgort(entity.getLgort());
            model.setBatch(entity.getBatch());
            model.setMatnr(entity.getMatnr());
            model.setMaktx(entity.getMaktx());
            model.setWarningDate(entity.getWarningDate());
            model.setCheckDate(entity.getCheckDate());
            model.setStoreDate(entity.getStoreDate());
            model.setMaxStoreDate(entity.getMaxStoreDate());
            model.setStatus(entity.getStatus());
            model.setCrname(entity.getCrname());
            model.setCrdate(entity.getCrdate());
            model.setChname(entity.getChname());
            model.setChdate(entity.getChdate());
            return model;
        }).collect(Collectors.toList());

8.一些计算,求和,求平均值

BigDecimal total = tOrderOrders.stream() .map(TOrderOrder::getAmount).reduce(BigDecimal.ZERO,BigDecimal::add);

list.stream().mapToDouble(User::getHeight).sum()//和
list.stream().mapToDouble(User::getHeight).max()//最大
list.stream().mapToDouble(User::getHeight).min()//最小
list.stream().mapToDouble(User::getHeight).average()//平均值

 //求和
BigDecimalrunTimeSum=failureRateGroupList.stream().map(EquipmentFailureRateEntity::getRunTime).reduce(BigDecimal.ZERO, BigDecimal::add);

获取map的随机一条数据

Map<String, String> errorMsgMap = new HashMap<String, String>();
        errorMsgMap.put("xixi","haha");
        errorMsgMap.put("huhu","dede");
        errorMsgMap.put("sisi","sdfd");
        errorMsgMap.put("gege","sfdg");
        Optional  optionalName = errorMsgMap.entrySet().stream()
               // .filter(e -> "dede".equals(e.getValue()))
                .map(Map.Entry::getValue).findFirst();
        String aa = (String) optionalName.get();
        System.out.println(aa);

集合排序改变原集合

 charList.sort(Comparator.comparing(EquipmentMaintenanceResultDto ::getCumulativeDate));

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值