本文方法及代码示例基于Kotlin 2.1.20 Released
groupingBy
所在包 kotlin.text.groupingBy
,其相关用法介绍如下:
用法:
kotlin
inline fun <K> CharSequence.groupingBy(
crossinline keySelector: (Char) -> K
): Grouping<Char, K>
从 char 序列创建一个 Grouping 源,以便稍后与 group-and-fold 操作之一一起使用,使用指定的 keySelector 函数从每个字符中提取一个键。
代码示例:
kotlin
fun main(args: Array<String>) {
//sampleStart
val words = "one two three four five six seven eight nine ten".split(' ')
val frequenciesByFirstChar = words.groupingBy { it.first() }.eachCount()
println("Counting first letters:")
println(frequenciesByFirstChar) // {o=1, t=3, f=2, s=2, e=1, n=1}
val moreWords = "eleven twelve".split(' ')
val moreFrequencies = moreWords.groupingBy { it.first() }.eachCountTo(frequenciesByFirstChar.toMutableMap())
println(moreFrequencies) // {o=1, t=4, f=2, s=2, e=2, n=1}
//sampleEnd
}
// 输出
Counting first letters:
{o=1, t=3, f=2, s=2, e=1, n=1}
{o=1, t=4, f=2, s=2, e=2, n=1}
相关方法
- Kotlin contentToString用法及代码示例
- Kotlin dropWhile用法及代码示例
- Kotlin distinct用法及代码示例
- Kotlin code用法及代码示例
- Kotlin Map:mapOf()用法及代码示例
- Kotlin distinctBy用法及代码示例
- Kotlin digitToChar用法及代码示例
- Kotlin ifBlank用法及代码示例
- Kotlin all用法及代码示例
- Kotlin digitToIntOrNull用法及代码示例
- Kotlin dropLast用法及代码示例
- Kotlin dropLastWhile用法及代码示例
- Kotlin associateBy用法及代码示例