reduceTo
所在位置是kotlin.collections.reduceTo
,其相關用法介紹如下。
用法:
inline fun <S, T : S, K, M : MutableMap<in K, S>> Grouping<T, K>.reduceTo(
destination: M,
operation: (key: K, accumulator: S, element: T) -> S
): M
按鍵對Grouping源中的元素進行分組,並從組的第二個元素開始依次對每個組的元素應用減少operation,將先前累積的值和當前元素作為參數傳遞,並將結果存儲在給定的destination Map。累加器的初始值是組的第一個元素。
如果 destination 映射已經具有與某個組的鍵對應的值,則該值用作該組的累加器的初始值,並且該組的第一個元素也受製於 operation 。
例子:
fun main(args: Array<String>) {
//sampleStart
val animals = listOf("raccoon", "reindeer", "cow", "camel", "giraffe", "goat")
val maxVowels = mutableMapOf<Char, String>()
// grouping by first char and collect only max of contains vowels
val compareByVowelCount = compareBy { s: String -> s.count { it in "aeiou" } }
animals.groupingBy { it.first() }.reduceTo(maxVowels) { _, a, b -> maxOf(a, b, compareByVowelCount) }
println(maxVowels) // {r=reindeer, c=camel, g=giraffe}
val moreAnimals = listOf("capybara", "rat")
moreAnimals.groupingBy { it.first() }.reduceTo(maxVowels) { _, a, b -> maxOf(a, b, compareByVowelCount) }
println(maxVowels) // {r=reindeer, c=capybara, g=giraffe}
//sampleEnd
}
輸出:
{r=reindeer, c=camel, g=giraffe} {r=reindeer, c=capybara, g=giraffe}
參數
operation
- 使用以下參數對組的每個後續元素調用的函數:
返回 destination 映射,將每個組的鍵與累積組元素的結果相關聯。
相關用法
- Kotlin reduceRight用法及代碼示例
- Kotlin reduceIndexed用法及代碼示例
- Kotlin reduceRightIndexed用法及代碼示例
- Kotlin reduceIndexedOrNull用法及代碼示例
- Kotlin reduce用法及代碼示例
- Kotlin reduceRightIndexedOrNull用法及代碼示例
- Kotlin reduceRightOrNull用法及代碼示例
- Kotlin reduceOrNull用法及代碼示例
- Kotlin reversed用法及代碼示例
- Kotlin replaceFirstChar用法及代碼示例
- Kotlin replace用法及代碼示例
- Kotlin runningReduceIndexed用法及代碼示例
- Kotlin rangeTo用法及代碼示例
- Kotlin runningFoldIndexed用法及代碼示例
- Kotlin runningReduce用法及代碼示例
- Kotlin runningFold用法及代碼示例
- Kotlin associateBy用法及代碼示例
- Kotlin all用法及代碼示例
- Kotlin map用法及代碼示例
- Kotlin filterNot用法及代碼示例
- Kotlin Random.Default用法及代碼示例
- Kotlin Byte.inc用法及代碼示例
- Kotlin getValue用法及代碼示例
- Kotlin Double.dec用法及代碼示例
- Kotlin windowedSequence用法及代碼示例
注:本文由純淨天空篩選整理自kotlinlang.org大神的英文原創作品 kotlin.collections.reduceTo。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。