Stream流求总和及取平均值

1、对于Integer类型,可以通过mapToInt转成IntStream流。IntStream流提供了sum和average方法直接求总和及取平均值,注意平均值返回类型为Double带小数。
2、对于BigDecimal类型,需要通过reduce方法手动求出总和sum,然后通过“sum/个数”的形式求平均值avg,注意取平均值时需要指定舍入模式RoundingMode,一般使用四舍五入(RoundingMode.HALF_UP)。

public class Test {

    public static void main(String[] args) {
        List<User> list = Arrays.asList(
                new User("小赵", 20, new BigDecimal("123.33"), DateUtil.parseDateTime("2014-5-18 23:12:29")),
                new User("小钱", 9, new BigDecimal("89.12"), DateUtil.parseDateTime("2023-2-18 06:45:12")),
                new User("小孙", 18, new BigDecimal("280.28"), DateUtil.parseDateTime("2009-3-31 16:33:45")),
                new User("小李", 13, new BigDecimal("1000.99"), DateUtil.parseDateTime("1992-12-4 10:48:08"))
        );
        list.forEach(System.out::println);
        System.out.println();

        //Integer
        int sum1 = list.stream().mapToInt(User::getAge).sum();
        System.out.println("Integer总和" + sum1);
        OptionalDouble avg1 = list.stream().mapToInt(User::getAge).average();
        avg1.ifPresent(e -> System.out.println("Integer平均值" + e));

        //BigDecimal
        BigDecimal sum2 = list.stream().map(User::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        System.out.println("BigDecimal总和" + sum2);
        BigDecimal avg2 = sum2.divide(new BigDecimal(list.size()), RoundingMode.HALF_UP);
        System.out.println("BigDecimal平均值" + avg2);
    }

}

@Data
@ToString
@AllArgsConstructor
class User {

    private String name;

    private Integer age;

    private BigDecimal money;

    private Date birthday;

}
User(name=小赵, age=20, money=123.33, birthday=2014-05-18 23:12:29)
User(name=小钱, age=9, money=89.12, birthday=2023-02-18 06:45:12)
User(name=小孙, age=18, money=280.28, birthday=2009-03-31 16:33:45)
User(name=小李, age=13, money=1000.99, birthday=1992-12-04 10:48:08)

Integer总和60
Integer平均值15.0
BigDecimal总和1493.72
BigDecimal平均值373.43

觉得内容还不错?打赏个钢镚鼓励鼓励!!👍