kotlin.text.groupBy

groupBy

inline fun <K> CharSequence.groupBy(
    keySelector: (Char) -> K
): Map<K, List<Char>>

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

The returned map preserves the entry iteration order of the keys produced from the original char sequence.

import kotlin.test.*
import java.util.*

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
}
inline fun <K, V> CharSequence.groupBy(
    keySelector: (Char) -> K, 
    valueTransform: (Char) -> V
): Map<K, List<V>>

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 returns a map where each group key is associated with a list of corresponding values.

The returned map preserves the entry iteration order of the keys produced from the original char sequence.

import kotlin.test.*
import java.util.*

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
}

© 2010–2017 JetBrains s.r.o.
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/group-by.html

在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号

意见反馈
返回顶部