3

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 ...
1
  • Be careful with solutions that "simply" split by ;. If the country name has a ; escaped, the simple solution will cut the field with the ;. Commented Jun 29, 2022 at 6:40

3 Answers 3

4
csv
  .split("\n")
  .groupBy({ it.substringAfter(";") }) { it.substringBefore(";") }})
Sign up to request clarification or add additional context in comments.

Comments

3

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 }

Comments

2

Alternatively to sidgate's excellent answer you could also do

csv.split("\n").groupBy({
    it.split(";")[1]
}){
    it.split(";")[0]
}

It avoids having to create a map first, but calls split more often. I'm not sure what would be better in terms of speed/efficiency.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.