reduceTo所在位置是kotlin.collections.reduceTo,其相關用法介紹如下。

用法:

inline fun <S, T : S, K, M : MutableMap<in K, S>> Grouping<T, K>.reduceTo(
    destination: M, 
    operation: (keyK, 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 映射,將每個組的鍵與累積組元素的結果相關聯。