Kotlin:列表中BigDecimal的和

我有一个我想要过滤的列表,然后返回一个id与金额总和的地图:

val totalById = list .filter { it.status == StatusEnum.Active } .groupBy { it.item.id } .mapValues { it.value.sumBy { it.amount } } 

“it.amount”是BigDecimal,但看起来像sumBy只是Int。

对于Java 8,它会是:

Collectors.groupingBy(i-> i.getItem().getId(), Collectors.mapping(Item::getAmount, Collectors.reducing(BigDecimal.ZERO, BigDecimal::add))))

Kotlin有没有办法做到这一点?

就像你用java中的Collectors.reducing一样,你可以在Kotlin中使用fold或者reduce扩展函数:

 val bigDecimals: List = ... val sum = bigDecimals.fold(BigDecimal.ZERO) { acc, e -> acc + e } // or val sum2 = bigDecimals.fold(BigDecimal.ZERO, BigDecimal::add) 

您可以创建类似于sumByDouble自己的sumByBigDecimal 扩展函数 。 例如:

 /** * Returns the sum of all values produced by [selector] function applied to each element in * the collection. */ inline fun  Iterable.sumByBigDecimal(selector: (T) -> BigDecimal): BigDecimal { var sum: BigDecimal = BigDecimal.ZERO for (element in this) { sum += selector(element) } return sum } 

用法示例:

 val totalById = list .filter { it.status == StatusEnum.Active } .groupBy { it.item.id } .mapValues { it.value.sumByBigDecimal { it.amount } }