当前位置:网站首页>The list set is summed up according to a certain attribute of the object, the maximum value, etc

The list set is summed up according to a certain attribute of the object, the maximum value, etc

2022-07-05 15:58:00 Ant HJK

First initialize the collection and add data

// Entity class
public class Student {
    private int mathScoresInt; // Math scores
    private long mathScoresLong;// Math scores
    private float mathScoresFloat;// Math scores
    private double mathScoresDouble;// Math scores
    private BigDecimal mathScoresBigDecimal;// Math scores
    // Construction method ignored
    //set、get Method ignored
}

// Test data   ( Don't allow list There is a null value in , Otherwise, it will be abnormal ! )
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)));

Tips : The following calculation is int 、long 、float 、double 、BigDecimal  Other types

One 、 according to List A property of an object in , Sum up

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);

Two 、 according to List A property of an object in , averaging

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);

3、 ... and 、 according to List A property of an object in , For maximum

int mathMaxInt = list.stream().mapToInt( Student::getMathScoresInt ).max().getAsInt(); //int type
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);

Four 、 according to List A property of an object in , For the minimum

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);

 

原网站

版权声明
本文为[Ant HJK]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207051526232425.html