java Stream 有Null值 求最大值最小值,平均值

 @ResponseBody
    @GetMapping("/getRainCalculate")
    public R getRainCalculate(@RequestParam Map<String, Object> params) {
        //查询列表数据
        List<PptnRDTO> pptnRList = pptnRService.getRainCalculate(params);

        Comparator<PptnRDTO> userComparator = Comparator.comparing(PptnRDTO::getDrp);
        //最大值
        BigDecimal max = null;
        String maxStnm = null;
        Optional<PptnRDTO> optional = pptnRList.stream().filter(PptnRDTO->PptnRDTO.getDrp()!=null).max(userComparator);
        if(optional != null && optional.isPresent()) {
            max = optional.get().getDrp();
            maxStnm = optional.get().getStnm();
        }
        //最小值
        BigDecimal min = null;
        String minStnm = null;
        Optional<PptnRDTO> optionalMin = pptnRList.stream().filter(PptnRDTO->PptnRDTO.getDrp()!=null).min(userComparator);
        if(optionalMin != null && optionalMin.isPresent()) {
            min = optionalMin.get().getDrp();
            minStnm = optionalMin.get().getStnm();
        }
        //求平均值
        BigDecimal average = pptnRList.stream().map(vo -> ObjectUtils.isEmpty(vo.getDrp()) ? new BigDecimal(0) : vo.getDrp()).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(pptnRList.size()), 2, BigDecimal.ROUND_HALF_UP);

        return R.ok().put("max", max).put("maxStnm",maxStnm).put("min", min).put("minStnm",minStnm).put("average", average);
    }

Guess you like

Origin blog.csdn.net/yuzheh521/article/details/118489768