• list集合根据对象某属性求和,最大值等


    先初始化集合并添加数据

    //实体类
    public class Student {
        private int mathScoresInt; //数学成绩
        private long mathScoresLong;//数学成绩
        private float mathScoresFloat;//数学成绩
        private double mathScoresDouble;//数学成绩
        private BigDecimal mathScoresBigDecimal;//数学成绩
        //构造方法忽略
        //set、get 方法忽略
    }

    //测试数据   ( 不允许list中存在为空的值,不然会异常! )
    List<Student> list = new ArrayList();
    list.add(new Student(87, 87, 87.5f, 87.8, new BigDecimal(87)));
    list.add(new Student(88, 88, 88.5f, 88.8, new BigDecimal(88)));
    list.add(new Student(89, 89, 89.5f, 89.8, new BigDecimal(89)));
    list.add(new Student(90, 90, 90.5f, 90.8, new BigDecimal(90)));

    提示:以下计算为int 、long 、float 、double 、BigDecimal 等类型

    一、根据List中的对象的某个属性,求和

    double mathAverageInt = list.stream().mapToInt( Student::getMathScoresInt ).average().orElse(0d);
    double mathAverageLong = list.stream().mapToLong( Student::getMathScoresLong ).average().orElse(0d);
    double mathAverageDouble = list.stream().mapToDouble( Student::getMathScoresDouble ).average().orElse(0d);

    二、根据List中的对象的某个属性,求平均值

    double mathAverageInt = list.stream().mapToInt( Student::getMathScoresInt ).average().orElse(0d);
    double mathAverageLong = list.stream().mapToLong( Student::getMathScoresLong ).average().orElse(0d);
    double mathAverageDouble = list.stream().mapToDouble( Student::getMathScoresDouble ).average().orElse(0d);

    三、根据List中的对象的某个属性,求最大值

    int mathMaxInt = list.stream().mapToInt( Student::getMathScoresInt ).max().getAsInt(); //int类型
    long mathMaxLong = list.stream().mapToLong( Student::getMathScoresLong ).max().getAsLong();
    double mathMaxDouble = list.stream().mapToDouble( Student::getMathScoresDouble ).max().getAsDouble();
    BigDecimal mathMaxBigDecimal = list.stream().map( Student::getMathScoresBigDecimal ).reduce(BigDecimal.ZERO, BigDecimal::max);

    四、根据List中的对象的某个属性,求最小值

    int mathMinInt = list.stream().mapToInt( Student::getMathScoresInt ).min().getAsInt();
    long mathMinLong = list.stream().mapToLong( Student::getMathScoresLong ).min().getAsLong();
    double mathMinDouble = list.stream().mapToDouble( Student::getMathScoresDouble ).min().getAsDouble();
    BigDecimal mathMinBigDecimal = list.stream().map( Student::getMathScoresBigDecimal ).reduce(BigDecimal.ZERO, BigDecimal::min);

     

  • 相关阅读:
    JSP高校考勤管理系统免费源代码+LW
    bootstrap柵格
    java封装和四种权限修饰符
    强势来袭!系统分析师,全面资料分享!
    TIPC Getting Started6
    QTableView对自定义的Model排序
    在virtualbox上搭建kubenetes集群入门
    阿里云产品试用系列-云桌面电脑
    国有林场试点森林防火(资源监管)四位一体系统建设指南
    leetcode-49.字母异位词分组
  • 原文地址:https://blog.csdn.net/weixin_43167662/article/details/125554674