Kotlin 对列表中数字的子集求和
在Kotlin中,有没有一种方法可以对过滤后的数字列表执行Kotlin 对列表中数字的子集求和,kotlin,Kotlin,在Kotlin中,有没有一种方法可以对过滤后的数字列表执行sum()操作,而不首先过滤掉元素 我在找这样的东西: val nums = listOf<Long>(-2, -1, 1, 2, 3, 4) val sum = nums.sum(it > 0) val nums=listOf(-2,-1,1,2,3,4) val sum=nums.sum(它>0) 您可以使用Iterable.sumBy: /** * Returns the sum of all values p
sum()
操作,而不首先过滤掉元素
我在找这样的东西:
val nums = listOf<Long>(-2, -1, 1, 2, 3, 4)
val sum = nums.sum(it > 0)
val nums=listOf(-2,-1,1,2,3,4)
val sum=nums.sum(它>0)
您可以使用Iterable.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
}
然后,可以取消toInt()
转换
nums.sumByLong { if (it > 0) it else 0 }
正如@Ruckus T-Boom所建议的那样,if(it>0)it else 0
可以使用返回值本身或给定最小值的Long.胁迫最小值()
进行简化:
nums.sumByLong { it.coerceAtLeast(0) }
您可以使用
it.compresseatlist(0)
而不是if(it>0)it else 0
nums.sumByLong { if (it > 0) it else 0 }
nums.sumByLong { it.coerceAtLeast(0) }
data class Product(val name: String, val quantity: Int) {
}
fun main(args: Array<String>) {
val productList = listOf(
Product("A", 100),
Product("B", 200),
Product("C", 300)
)
val totalPriceInList1: Int = productList.map { it.quantity }.sum()
println("sum(): " + totalPriceInList1)
val totalPriceInList2: Int = productList.sumBy { it.quantity }
println("sumBy(): " + totalPriceInList2)
}
sum(): 600
sumBy(): 600