I have a list :
field = ["key1.value1", "key1.value2", "key2.value3"]
that I want to transform into a Map<String, List<String>> such as
attributes = {"key1"=["value1", "value2"], "key2"=["value3"]}
The following works pretty well :
for (elem in field) {
val key = elem.split(".").first()
val value = elem.split(".").last()
if (key in attributes.keys) attributes[key]!!.add(value)
else {
attributes[key] = mutableListOf()
attributes[key]!!.add(value)
}
}
but it's not very kotlin-like. I tried with associateByTo:
val attributes = mutableMapOf<String, List<String>>()
field.associateByTo(
destination = attributes,
keySelector = { it.split(".").first() },
valueTransform = { mutableListOf(it.split(".").last()) }
)
but this only keeps the last value, as said in the doc. How can I build such a map in a kotlin way?