List中的对象属性 求和、最大值、最小值、平均值( int、long、double、BigDecimal)

public class ListCalculate {
    public static void main(String[] args) {
        List<Money> moneyList = getMoneyList();
        // List中的对象属性 求和
        int sumInt = moneyList.stream().mapToInt(Money::getAmountInt).sum();
        long sumLong = moneyList.stream().mapToLong(Money::getAmountLong).sum();
        double sumDouble = moneyList.stream().mapToDouble(Money::getAmountDouble).sum();
        BigDecimal sumBigDecimal = moneyList.stream().map(Money::getAmountBigDecimal).reduce(BigDecimal.ZERO, BigDecimal::add);

        // List中的对象属性 求最大值
        int maxInt = moneyList.stream().mapToInt(Money::getAmountInt).max().getAsInt();
        long maxLong = moneyList.stream().mapToLong(Money::getAmountLong).max().getAsLong();
        double maxDouble = moneyList.stream().mapToDouble(Money::getAmountDouble).max().getAsDouble();
        BigDecimal maxBigDecimal = moneyList.stream().map(Money::getAmountBigDecimal).reduce(BigDecimal.ZERO, BigDecimal::max);

        // List中的对象属性 求最小值  注意BigDecimal
        int minInt = moneyList.stream().mapToInt(Money::getAmountInt).min().getAsInt();
        long minLong = moneyList.stream().mapToLong(Money::getAmountLong).min().getAsLong();
        double minDouble = moneyList.stream().mapToDouble(Money::getAmountDouble).min().getAsDouble();
        BigDecimal minBigDecimal = moneyList.stream().map(Money::getAmountBigDecimal).reduce(BigDecimal.ZERO, BigDecimal::min); // 0
        BigDecimal minBigDecimal2 = moneyList.stream().map(Money::getAmountBigDecimal).min(BigDecimal::compareTo).get(); // 143
        ;

        // List中的对象属性 求平均值
        double averageInt = moneyList.stream().mapToInt(Money::getAmountInt).average().getAsDouble();
        double averageLong = moneyList.stream().mapToLong(Money::getAmountLong).average().getAsDouble();
        double averageDouble = moneyList.stream().mapToDouble(Money::getAmountDouble).average().getAsDouble();
        BigDecimal averageBigDecimal = moneyList.stream().map(Money::getAmountBigDecimal).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(moneyList.size()), 2, RoundingMode.HALF_UP);

    }

    private static List<Money> getMoneyList() {
        List<Money> moneyList = new ArrayList<>();
        moneyList.add(new Money(111, 958L, 333.5, new BigDecimal(689)));
        moneyList.add(new Money(723, 256L, 999.0, new BigDecimal(333)));
        moneyList.add(new Money(135, 780L, 843.8, new BigDecimal(276)));
        moneyList.add(new Money(564, 671L, 745.1, new BigDecimal(143)));
        return moneyList;
    }
}

@Data
@AllArgsConstructor
class Money {
    private int amountInt;
    private long amountLong;
    private double amountDouble;
    private BigDecimal amountBigDecimal;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值