The easiest way to convert a string to a HashMap

if I have text in a string, for example:

"ABC = 123, DEF = 456, GHI = 789"

how can I create a populated object for it HashMap<String,Int>in the lightest and shortest amount of code in Kotlin?

+4
source share
1 answer

I don't think the solution is simpler 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 it HashMap, use it .associateTo(HashMap()) { ... }.

Some information:

+9

Source: https://habr.com/ru/post/1664094/


All Articles