Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin convert csv to map <String, List>

Tags:

kotlin

I have following CSV

US;Americas
CA;Americas
FR;Europe
CH;Asia
...

I want to have Map of -> String, List, is it possible to achieve this via associate, or something else ?

So far I have this:

csv.split("\n").associate { 
  val (code, region) = it.split(";") 
  region to code 
}

but this is just mapping the region to only one code, also tried

region to listOf(code)

expected result:

Americas -> US, CA, BR ...
Europe -> FR, IT, CH ...
Asia -> CH, JP, KR ...
like image 641
Master Yi Avatar asked Mar 10 '26 22:03

Master Yi


2 Answers

csv
  .split("\n")
  .groupBy({ it.substringAfter(";") }) { it.substringBefore(";") }})
like image 80
lukas.j Avatar answered Mar 13 '26 18:03

lukas.j


associate would replace the value if the key already iterated. You can instead use groupBy to specify key and value for the map

csv.split("\n").map {
    val (code, region) = it.split(";")
    region to code
}.groupBy({ it.first }) { it.second }
like image 25
sidgate Avatar answered Mar 13 '26 16:03

sidgate