我有一个要过滤的列表,然后返回一个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))))
在科特林有办法吗?
发布于 2016-09-30 15:44:23
就像在java中使用Collectors.reducing一样,您可以在Kotlin中使用fold或reduce扩展函数:
val bigDecimals: List<BigDecimal> = ...
val sum = bigDecimals.fold(BigDecimal.ZERO) { acc, e -> acc + e }
// or
val sum2 = bigDecimals.fold(BigDecimal.ZERO, BigDecimal::add)关于play.kotlinlang.org:https://pl.kotl.in/o6pRhrqys的完整示例
从Kotlin 1.4开始,现在有一个函数sumOf,它接受一个选择器函数并对这个选择器返回的所有值进行求和,因此您可以如下所示:
val totalById = list
.groupBy { it.id }
.mapValues { it.value.sumOf { it.amount } }关于play.kotlinlang.org:https://pl.kotl.in/jXAfoyff-的完整示例
发布于 2016-09-30 14:35:36
您可以创建自己的sumByBigDecimal 扩展函数,类似于sumByDouble。例如:
/**
* Returns the sum of all values produced by [selector] function applied to each element in
* the collection.
*/
inline fun <T> Iterable<T>.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 } }发布于 2020-10-26 12:02:31
在Kotlin1.4中,他们引入了sumOf,它的用法:
val bigDecimals: List<BigDecimal> = ...
val sum = bigDecimals.sumOf { it }https://stackoverflow.com/questions/39793600
复制相似问题