Alex
Alex

Reputation: 1934

Increment Key-Value from a for loop to a map

I have this map

    var alphabet= mutableMapOf("a" to 1)

And i would like to add from a for loop all the letters of the alphabet and their numbers. For example: a=1 b=2 ... z=26

How can i add ++ to keys and values in a map?

Upvotes: 0

Views: 469

Answers (1)

awesoon
awesoon

Reputation: 33671

Just iterate over chars range:

val alphabet = mutableMapOf<Char, Int>()
for (c in 'a'..'z') {
    alphabet[c] = c - 'a' + 1;
}

Also if you are not planning to change this map after initialization I do not think you really need a map here, just a function for c - 'a' + 1 with proper range checks will be enough.

Upvotes: 1

Related Questions