reduceTo

Common
JVM
JS
Native
1.1
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

(source)

Groups elements from the Grouping source by key and applies the reducing operation to the elements of each group sequentially starting from the second element of the group, passing the previously accumulated value and the current element as arguments, and stores the results in the given destination map. An initial value of accumulator is the first element of the group.

If the destination map already has a value corresponding to the key of some group, that value is used as an initial value of the accumulator for that group and the first element of that group is also subjected to the 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
}

Parameters

operation - a function that is invoked on each subsequent element of the group with the following parameters:

Return the destination map associating the key of each group with the result of accumulating the group elements.