sort object list kotlin
To sort a list of objects in Kotlin, you can use the sortedWith
function along with a comparator. Here's an example of how to do this:
data class Person(val name: String, val age: Int)
fun main() {
val people = listOf(Person("Alice", 29), Person("Bob", 31), Person("Charlie", 25))
val sortedPeople = people.sortedWith(compareBy { it.age })
println(sortedPeople)
}
In this example, we have a data class called Person
with properties name
and age
. We create a list of Person
objects and then use the sortedWith
function with the compareBy
function to sort the list based on the age
property of each person. The compareBy
function is a shorthand for creating a comparator that compares the specified property.
When we run this code, the sortedPeople
list will contain the Person
objects sorted by their age in ascending order.