-
Notifications
You must be signed in to change notification settings - Fork 23
Collection: Sorting a collection of objects based on a parameter in the object
Devrath edited this page Feb 29, 2024
·
1 revision
Observation This is handy instead of using the comparator where kotlin does this out of the box
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),
)
fun main(args: Array<String>) {
countriesList.sortBy {
it.name
}
countriesList.forEach {
println(it.name)
}
}
Output
Australia
England
North Korea
Russia
USA