Aleksandr Wake
Aleksandr Wake

Reputation: 91

How to convert List<String> to Map<String, Int> in Kotlin?

For example I have a list of strings like:

val list = listOf("a", "b", "a", "b" "a" "c") and I need to convert it to a Map, where the strings are the keys and values are count of repetitions. So i have to got Map like [a = 3] [b = 2] [c = 1]

Upvotes: 2

Views: 437

Answers (1)

lukas.j
lukas.j

Reputation: 7163

val list = listOf("a", "b", "a", "b", "a", "c")

val result = list.groupingBy { it }.eachCount()

// result is Map<String, Int> looking like this: {a=3, b=2, c=1}

Edit: for counts bigger than 1 add a filter condition to the map

val result = list.groupingBy { it }.eachCount().filter { it.value > 1 }

// result is now: {a=3, b=2}

Upvotes: 2

Related Questions