Java Integer、Long、Double类型数值求平均值

1 Integer类型数值求平均值
1.1 常规实现

List<Integer> list = new ArrayList<>();
Integer sum = 0;
for (Integer i : list) {
sum += i;
}
double avg = list != null && list.size() > 0 ? sum * 1.0 / list.size() : 0;

1.2 Collectors.averagingInt()

List<Integer> list = new ArrayList<>();
double avg = list.stream().collect(Collectors.averagingInt(x -> x));

2 Long类型数值求平均值
2.1 常规实现

List<Long> list = new ArrayList<>();
Long sum = 0;
for (Long i : list) {
sum += i;
}
double avg = list != null && list.size() > 0 ? sum * 1.0 / list.size() : 0;

2.2 Collectors.averagingLong()

List<Long> list = new ArrayList<>();
double avg = list.stream().collect(Collectors.averagingLong(x -> x));

3 Double类型数值求平均值
3.1 常规实现

List<Double> list = new ArrayList<>();
Double sum = 0;
for (Double i : list) {
sum += i;
}
double avg = list != null && list.size() > 0 ? sum / list.size() : 0;

3.2 Collectors.averagingDouble()

List<Double> list = new ArrayList<>();
double avg = list.stream().collect(Collectors.averagingDouble(x -> x));

————————————————
版权声明:本文为CSDN博主「旭东怪」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_38974638/article/details/119113735

posted on 2022-12-29 16:10  大山008  阅读(831)  评论(0)    收藏  举报