Arknes
Arknes

Reputation: 41

How to deconstruct map to list?

I have a List that contain country, I used groupBy to group them by country and now i would like to get fallowing result (for recycled view):

Country1
Airport1
Airport2
Airport3
Country2
Airport4
Airport5
Airport6

could someone give me a tip on how to do this? My data class:

data class Airport(
val city: City,
val code: String,
val country: Country,
val name: String,

)

Upvotes: 0

Views: 142

Answers (1)

k314159
k314159

Reputation: 11062

Assuming:

  • after you call groupBy you have a Map<Country, List<Airport>>
  • you want the countries to be in alphabetical order
  • you want to transform the map to a List<String>

This should do it:

airportsByCountry
    .toSortedMap()
    .flatMap { (country, airports) ->
        listOf(country.toString()) + airports.map { it.toString() }
    }

Upvotes: 2

Related Questions