Kotlin: Sum of BigDecimal in a list

In Kotlin 1.4 they introduced sumOf, usage of it:

val bigDecimals: List<BigDecimal> = ...
val sum = bigDecimals.sumOf { it }

documentation


You can create your own sumByBigDecimal extension function similar to sumByDouble. e.g.:

/**
 * 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
}

Example usage:

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

Just like you've used Collectors.reducing in java, you can use fold or reduce extension functions in Kotlin:

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

The full example on play.kotlinlang.org: https://pl.kotl.in/o6pRhrqys

Starting with Kotlin 1.4 there's now a function sumOf, that takes a selector function and sums all values returned by this selector, so you can use it as following:

val totalById = list
                .groupBy { it.id }
                .mapValues { it.value.sumOf { it.amount } }

The full example on play.kotlinlang.org: https://pl.kotl.in/jXAfoyff-

Tags:

Kotlin