21

if I have some text in a String like:

"abc=123,def=456,ghi=789"

how could I create a populated HashMap<String,Int> object for it in the easiest, shortest amount of code possible in Kotlin?

2 Answers 2

56

I can think of no solution easier than this:

val s = "abc=123,def=456,ghi=789"

val map = s.split(",").associate { 
    val (left, right) = it.split("=")
    left to right.toInt() 
}

Or, if you need exactly a HashMap, use .associateTo(HashMap()) { ... }.

Some details:

4

You can map each key/value to a Pair with the to keyword. An iterable of Pair can be mapped to a Map easily with the toMap() extension method.

val s = "abc=123,def=456,ghi=789"
val output = s.split(",")
              .map { it.split("=") }
              .map { it.first() to it.last().toInt() }
              .toMap()

Not the answer you're looking for? Browse other questions tagged or ask your own question.