2017-10-20 46 views
3

Kotlin有沒有在已過濾的數字列表上進行sum()操作的方法,但實際上並未首先過濾出元素?總結列表中的數字的一個子集

我正在尋找這樣的事情:

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

回答

4

您可以使用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值回來了,你必須寫一個擴展Long就像Iterable<T>.sumByDouble

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-臂架建議,if (it > 0) it else 0可以使用Long.coerceAtLeast()它返回該值本身,或者給定的最小值被簡化了:

nums.sumByLong { it.coerceAtLeast(0) } 
+2

可以使用'it.coerceAtLeast(0)'而不是「if(it> 0)else else」 –

相關問題