Home > front end >  flatten list with repeated element in kotlin
flatten list with repeated element in kotlin

Time:02-15

I have the following data class as a data transfer object.

data class Continent(
    val continent: String,
    val countries: List<String>
)

so the JSON response is like below.

{
  "content": [
       {
           "continent": "Europe",
           "countries": [
              "France",
              "Germany"
           ]
       }
  ]
}

However, what I want to do is this:

{
  "content": [
        {
            "continent": "Europe",
            "country": "France"
        },
        {
            "continent": "Europe",
            "country": "Germany"
        }
  ]
}

I suppose there must be some kotlin collection functions to apply. Since the dto i wrote in the first code block is unable to be moderated, i have to apply collection functions on the service layer and make response dto accordingly.

Could you please let me know? Thanks in advance.

CodePudding user response:

data class Country(
    val continent: String,
    val country: String
)

fun List<ContinentResponse>.toCountries(): List<Country> =
    flatMap { r -> r.countries.map { country -> Country(r.continent, country) } }
  • Related