pbount
pbount

Reputation: 1803

How can I create a map of the characters of a string and the number of their occurances in Kotlin?

I have a string "Hello World"

I need a Map<Char, Int> which will contain the pairs of each character and the number of times it appears in the string : {H=1, e=1, l=3, o=2,r=1, d=1}

How can I do that without using the traditional for loop?

Upvotes: 3

Views: 1121

Answers (1)

Willi Mentzel
Willi Mentzel

Reputation: 29844

Do it like this

val map = "Hello World".groupingBy { it }.eachCount()

map will be of type Map<Char, Int>

Upvotes: 11

Related Questions