在列表中总结一部分数字

Kotlin有没有办法在经过筛选的数字列表上进行sum()操作,而不是先实际过滤掉元素?

我正在寻找这样的东西:

 val nums = listOf<Long>(-2, -1, 1, 2, 3, 4) val sum = nums.sum(it > 0) 

你可以使用Iterable<T>.sumBy

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

你可以传递一个函数给函数将负值转换为0.所以,它将列表中所有大于0的值加起来,因为加0不会影响结果。

 val nums = listOf<Long>(-2, -1, 1, 2, 3, 4) val sum = nums.sumBy { if (it > 0) it.toInt() else 0 } println(sum) //10 

如果您需要Long值,则必须像Iterable<T>.sumByDouble一样为Long写一个扩展名。

 inline fun <T> Iterable<T>.sumByLong(selector: (T) -> Long): Long { var sum: Long = 0 for (element in this) { sum += selector(element) } return sum } 

然后, toInt()转换可以被拿走。

  nums.sumByLong { if (it > 0) it else 0 } 

正如@Ruckus T-Boom建议的那样, if (it > 0) it else 0可以使用Long.coerceAtLeast()来简化,返回值本身或给定的最小值:

 nums.sumByLong { it.coerceAtLeast(0) }