Add a toMap overload that takes a pair producing lambda

I’ve sometimes found myself writing code like:

val map = value.split(';').map {
    it.split('=').let { parts -> parts[0] to parts[1] }
}.toMap()

This is somewhat inefficient as it is constructing a list as part of the map expression before converting it to a map.

It would be useful having a toMap variant that takes a lambda expression that produces the key/value pairs. This would then put the key/value pairs directly onto the map without creating an intermediate list first. – This is similar to the lambda versions of functions like joinToString.

val map = value.split(';').toMap {
    it.split('=').let { parts -> parts[0] to parts[1] }
}
1 Like

It’s already there, called associate

3 Likes

Thanks!