Home > Back-end >  How to transform a list to a map of lists in Kotlin?
How to transform a list to a map of lists in Kotlin?

Time:12-03

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?

CodePudding user response:

You can do this without intermediate collections by using groupBy directly:

val attributes = field.groupBy({ it.substringBefore(".") }, { it.substringAfter(".") })

Or to make it slightly more readable to the uninitiated:

val attributes = field.groupBy(
    keySelector = { it.substringBefore(".") },
    valueTransform = { it.substringAfter(".") },
)

CodePudding user response:

You need groupBy function

val result = field
    .map { it.split(".") }
    .groupBy({ it.first() }, { it.last() })
  • Related