W3cubDocs

/Kotlin

groupByTo

Platform and version requirements: JVM (1.0), JS (1.0), Native (1.0)
inline fun <K, M : MutableMap<in K, MutableList<Char>>> CharSequence.groupByTo(
    destination: M, 
    keySelector: (Char) -> K
): M

Groups characters of the original char sequence by the key returned by the given keySelector function applied to each character and puts to the destination map each group key associated with a list of corresponding characters.

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val words = listOf("a", "abc", "ab", "def", "abcd")
val byLength = words.groupBy { it.length }

println(byLength.keys) // [1, 3, 2, 4]
println(byLength.values) // [[a], [abc, def], [ab], [abcd]]

val mutableByLength: MutableMap<Int, MutableList<String>> = words.groupByTo(mutableMapOf()) { it.length }
// same content as in byLength map, but the map is mutable
println("mutableByLength == byLength is ${mutableByLength == byLength}") // true
//sampleEnd
}

Return The destination map.

Platform and version requirements: JVM (1.0), JS (1.0), Native (1.0)
inline fun <K, V, M : MutableMap<in K, MutableList<V>>> CharSequence.groupByTo(
    destination: M, 
    keySelector: (Char) -> K, 
    valueTransform: (Char) -> V
): M

Groups values returned by the valueTransform function applied to each character of the original char sequence by the key returned by the given keySelector function applied to the character and puts to the destination map each group key associated with a list of corresponding values.

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val nameToTeam = listOf("Alice" to "Marketing", "Bob" to "Sales", "Carol" to "Marketing")
val namesByTeam = nameToTeam.groupBy({ it.second }, { it.first })
println(namesByTeam) // {Marketing=[Alice, Carol], Sales=[Bob]}

val mutableNamesByTeam = nameToTeam.groupByTo(HashMap(), { it.second }, { it.first })
// same content as in namesByTeam map, but the map is mutable
println("mutableNamesByTeam == namesByTeam is ${mutableNamesByTeam == namesByTeam}") // true
//sampleEnd
}

Return The destination map.

© 2010–2020 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/group-by-to.html