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;
}
List中的对象属性 求和、最大值、最小值、平均值( int、long、double、BigDecimal)
最新推荐文章于 2024-07-20 03:08:11 发布