Tuesday, August 22, 2023

Kotlin - Convert list of String to Map with count of each element as value

 

Kotlin Code to transform List into Map with list elements as Key and value as count of each element. Map contains only unique keys.

 



fun main() {
    countListElements(listOf("Apple", "orange", "mango", "orange"))
}

fun countListElements(fruits: List String>) {
    val fruitMap = fruits.groupingBy { it }.eachCount()
    print(fruitMap)
}