- 
                Notifications
    
You must be signed in to change notification settings  - Fork 24
 
Collections: Associating the data using some key
        Devrath edited this page Feb 29, 2024 
        ·
        1 revision
      
    Observation
- The advantage here is observe we were able to convert the list of objects into a map by using one of the fields of the objects in the list of each item.
 - Also notice I had duplicate entry as key that was removed from output
 
Code
data class Country(val id : Int, val name: String, val isDemocracy: Boolean)
val countriesList = mutableListOf(
    Country(id = 1, name = "USA", isDemocracy = true),
    Country(id = 2, name = "Australia", isDemocracy = true),
    Country(id = 3, name = "Russia", isDemocracy = false),
    Country(id = 4, name = "England", isDemocracy = true),
    Country(id = 5, name = "North Korea", isDemocracy = false),
    Country(id = 5, name = "South Korea", isDemocracy = false)
)
fun main(args: Array<String>) {
    val mapOfObjects = countriesList.associateBy {
        it.id
    }
    mapOfObjects.forEach{
        println(it.value.name)
    }
}Output
USA
Australia
Russia
England
South Korea