Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

flatten list with repeated element in kotlin

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  "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.

>Solution :

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) } }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading