Java:根据List中的对象的某个属性:求和、最⼤、最⼩、平均值。(⽤
Stream)
//实体类
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中的对象的某个属性,求和
int mathSumInt = list.stream().mapToInt( Student::getMathScoresInt).sum();//int类型
long mathSumLong = list.stream().mapToLong( Student::getMathScoresLong).sum();//long类型
double mathSumDouble = list.stream().mapToDouble( Student::getMathScoresDouble).sum();//double类型
BigDecimal mathSumBigDecimal = list.stream().map( Student::getMathScoresBigDecimal).reduce(BigDecimal.ZERO, BigDecimal::add);//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中的对象的某个属性,求最⼤值
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();java stream
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);
五、学习链接

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。