Easiest way to convert a string into a HashMap

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()

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:

  • .associate { ... } receives a function that produces pairs which are then stored into a map as keys and values respectively.

  • val (left, right) = it.split("=") is the usage of destructuring declarations on the list returned from it.split("="), it takes the first two items from the list.

  • left to right.toInt() creates a Pair<String, Int> defining a single mapping.

Tags:

Parsing

Kotlin