How to group words by first letter in Kotlin

1 Answer

0 votes
/**
 * Groups words by their first letter.
 *
 * @param words List of words to group
 * @return Map where each key is a first letter, and each value is a list of words
 */
fun groupByFirstLetter(words: List<String>): Map<Char, List<String>> {
    // groupBy automatically creates a map: key -> list of items
    // { it.first() } extracts the first character of each word
    return words.groupBy { it.first() }
}

fun main() {
    // List of words to group
    val words = listOf(
        "Python", "JavaScript", "C", "Java", "C#", "PHP",
        "C++", "Pascal", "SQL", "Rust"
    )

    val grouped = groupByFirstLetter(words)

    // Print each group
    for ((letter, group) in grouped) {
        println("$letter: ${group.joinToString(prefix = "[", postfix = "]")}")
    }

    // Print the entire map
    println(grouped)
}



/*
run:

P: [Python, PHP, Pascal]
J: [JavaScript, Java]
C: [C, C#, C++]
S: [SQL]
R: [Rust]
{P=[Python, PHP, Pascal], J=[JavaScript, Java], C=[C, C#, C++], S=[SQL], R=[Rust]}

*/

 



answered Jan 17 by avibootz
...