1. List<Bean
java
public static <T> BigDecimal summary(List<T> list, Function<T, BigDecimal> getFieldFunction) {
Optional<List<T>> optionalList = Optional.ofNullable(list);
return optionalList.map(lst -> lst.stream()
.filter(Objects::nonNull) // 过滤掉空对象
.map(getFieldFunction)
.filter(Objects::nonNull) // 过滤掉提取的BigDecimal值为空的情况
.reduce(BigDecimal.ZERO, BigDecimal::add))
.orElse(BigDecimal.ZERO);
}
用法
java
BigDecimal collectServiceFee = ListUtils.summary(temuFinanceData, TemuFinanceData::getCollectServiceFee);
2.List<Map
java
/**
* 汇总某个字段的值
* @param list
* @param type
* @return
*/
public static BigDecimal summary(List<Map<String, Object>> list, String type) {
BigDecimal result = BigDecimal.ZERO;
if (CollectionUtils.isNotEmpty(list)) {
result = new BigDecimal(list.stream().mapToDouble(v -> v.get(type) != null ? Double.parseDouble(v.get(type).toString()) : 0).sum());
}
return result;
}
用法
java
ListUtils.summary(result, "主SKU个数")