Kotlin maps: counting and indexing

Kotlin has read-only Map and MutableMap types. mapOf and mutableMapOf keep the order of insertion when printed. groupingBy { key }.eachCount() counts how many elements share each key in one pass. getOrPut(key) { default } returns the existing value or creates and stores a new one, which is the clean way to build a map of lists.

Kotlin
fun main() {
    val text = "the cat and the hat and the bat"
    val freq = text.split(" ").groupingBy { it }.eachCount()
    println(freq.entries.sortedWith(compareBy({ -it.value }, { it.key })).joinToString(" ") { "${it.key}=${it.value}" })

    val index = mutableMapOf<Char, MutableList<String>>()
    for (word in listOf("apple", "avocado", "banana", "blueberry", "cherry")) {
        index.getOrPut(word[0]) { mutableListOf() }.add(word)
    }
    println(index)
    println(index['b']?.size ?: 0)
    println(index['z']?.size ?: 0)
}
Read the full lesson